Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从JavaScript函数更改数据属性?_Javascript_Vue.js - Fatal编程技术网

从JavaScript函数更改数据属性?

从JavaScript函数更改数据属性?,javascript,vue.js,Javascript,Vue.js,我是Vue的新手,我正在尝试使用函数更改此.data App.vue: data () { return { data: null } }, beforeMount: async function () { function something (response) { this.data = response } something('hello') console.log(this.data) } 错误: data () { return

我是Vue的新手,我正在尝试使用
函数更改
此.data


App.vue:

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

  something('hello')

  console.log(this.data)
}

错误:

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

  something('hello')

  console.log(this.data)
}
无法读取null的属性“数据”

“此”
在上下文中丢失。 阅读mozilla

使用箭头函数保留
或函数的范围

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

  something('hello')

  console.log(this.data)
}

只需使用方法部分

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

  console.log(this.data)
}

此错误是因为“This”未获取绑定上下文。 您可以使用箭头功能(推荐ES6方式)或使用绑定(此)功能


这可能是因为当您这样定义函数时,
这个
是有界的。尝试将函数定义为
constsomething=(response)=>{}
,看看这是否能解决问题。