3

I'm new in Vue and I'm trying to change this.data using a function.


App.vue:

data () {
  return {
    data: null
  }
},
beforeMount: async function () {
  function something (response) {
    this.data = response
  }

  something('hello')

  console.log(this.data)
}

Error:

Cannot read property 'data' of null

1
  • It's probably because this is being bounded when you define the function like that. try defining the function as const something = (response) => {} instead and see if that fixes it. Commented Dec 11, 2019 at 16:31

3 Answers 3

2

"this" is lost in context. read This Operator on mozilla

use arrow functions to preserve the scope of this, or bind the function

data () {
  return {
    data: null
  }
},
beforeMount: async function () {
  const something = (response) => {
    this.data = response
  }

  something('hello')

  console.log(this.data)
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just use the methods section.

data () {
  return {
    data: null
  }
},
methods: {
 update(response) {
   this.data = response
 }
},
beforeMount: async function () {
  this.update('hello')

  console.log(this.data)
}

Comments

0

This error is because of 'this' not getting the bind context. You can use either arrow function(Recommended ES6 way) or using bind(this) function

const something  = (response) => {
    this.data = response
  }

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.