I have a Vue.js component defined as following:
module.exports = Vue.component('folder-preview', {
props: ['name', 'path', 'children', 'open'],
template: `...
`,
methods: mapActions([
]),
computed: mapState([
]),
data: ()=> {
console.log(this);
return {
collapsed: (this.open !== 'true')
}
}
});
Basically, I'm trying to keep collapsed as data local to the component, but take the value passed in the prop as the initial value. However, it seems like this.open is always undefined. In fact, console.logging this prints an empty object, and I can't seem to figure why.
Am I getting something wrong?
The problem in your code is subtle: you've declared data as an arrow function.
As covered in this question, arrow functions get this from the context of definition, while regular functions get this from the calling context. Making data an arrow function means it won't receive the component scope correctly.
When declared as a regular function that doesn't scope this off, the component works fine.
Vue.component('sample', {
props: ['open'],
template: '<div>{{collapsed}}</div>',
data() {
return {
collapsed: this.open !== 'true'
}
}
})
new Vue({
el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<sample open="true"></sample>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With