0
votes

Error in data(): "TypeError: Cannot read property 'propsTitle' of undefined"

I cant initialize by props to data. it keeps showing me this error and I can't figure it out why? I read the vuejs tutorial it shows title: this.propsTitle this is the correct way. what am I missing? Thank everyone!

Error in data(): "TypeError: Cannot read property 'propsTitle' of undefined"

          props: {
            propsTitle: String, 
            propsLevel: Number,
            propsProgress: Number,
          },

          data: () => ({
            title: this.propsTitle,
            progress: this.propsLevel,
            level: this.propsLevel,
            activeBtnTxt: "Start",
            isStarted: false

          }),  
// watch: {
      //   progress(val) {
      //     this.progress = val
      //   }
      // },
      // mounted() {
      //   console.log(this.propsProgress)
      //   // this.progress = propsProgress
      //   // this.level = propsLevel
      //   // this.title = propsTitle
      // },
2

2 Answers

3
votes

This:

data: () => ({
    ...
})

Should be this:

data () {
    ...
}

If you use an arrow function you'll end up with the this reference pointing at the wrong object.

There is a note about this in the docs: https://vuejs.org/v2/api/#data

Note that if you use an arrow function with the data property, this won’t be the component’s instance...

0
votes

Here is the corrected code. You have to use a function with return.

  props: {
    propsTitle: String, 
    propsLevel: Number,
    propsProgress: Number,
  },

  data() {
    console.log(this)
    return { 
      title: this.propsTitle,
      progress: this.propsProgress,
      level: this.propsLevel,
      activeBtnTxt: "Start",
      isStarted: false
    }
  },