Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change data prop from JavaScript function?

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

like image 403
Hristo Torbov Avatar asked Dec 21 '25 18:12

Hristo Torbov


1 Answers

"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)
}
like image 149
Cristyan Avatar answered Dec 23 '25 10:12

Cristyan