Sh031224
Sh031224

Reputation: 809

(Vue.js) In computed, I can't use data

export default {
  data () {
    return {
      test: true
    }
  },
  computed: {
    test2: {
      get: () => {
        return console.log(this.test)
      },
      set: () => {
        console.log(this.test)
      }
  }
}

But the Error occurred
TypeError: Cannot read property 'test' of undefined

I want to use data in computed. but I can't Help Me!

Upvotes: 0

Views: 764

Answers (2)

Terry
Terry

Reputation: 66228

You should not be using arrow functions in the getter and setters, because that refers to the lexical this:

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

So, update your code:

export default {
  data () {
    return {
      test: true
    }
  },
  computed: {
    test2: {
      get: function () {
        return console.log(this.test)
      },
      set: function () {
        console.log(this.test)
      }
  }
}

Upvotes: 4

mai elrefaey
mai elrefaey

Reputation: 392

this here refers to the function not vue instance ,you can make this:

test2: {
let This = this
      get: () => {
        return console.log(This.test)
      },
      set: () => {
        console.log(This.test)
      }
  }

Upvotes: 0

Related Questions