3

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?

byteSlayer
  • 1,806
  • 5
  • 18
  • 36
  • What happens if you print `this.open` in `created` (add a property `created` like how you add `props`, `data` and `computed`, and like `data`, `created` takes a function)? – kevguy Sep 15 '17 at 01:12
  • why can you not use open in you props as collaosed and set the value in parent element – usrNotFound Sep 15 '17 at 01:12
  • @kevguy in created `this` is also empty – byteSlayer Sep 15 '17 at 01:15
  • @usrNotFound what sets the collapsed is the component itself. The parent shouldn't care / doesn't need to be aware of it. It's internal to the component – byteSlayer Sep 15 '17 at 01:16
  • 2
    Possible duplicate of [VueJS: why is "this" undefined?](https://stackoverflow.com/questions/43929650/vuejs-why-is-this-undefined) – Roy J Sep 15 '17 at 01:18

1 Answers1

3

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>
Etheryte
  • 24,589
  • 11
  • 71
  • 116