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?

5
  • 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)? Commented Sep 15, 2017 at 1:12
  • why can you not use open in you props as collaosed and set the value in parent element Commented Sep 15, 2017 at 1:12
  • @kevguy in created this is also empty Commented Sep 15, 2017 at 1: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 Commented Sep 15, 2017 at 1:16
  • 2
    Possible duplicate of VueJS: why is "this" undefined? Commented Sep 15, 2017 at 1:18

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.