从JavaScript函数更改数据属性?
我是Vue的新手,我正在尝试使用从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
函数更改此.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)=>{}
,看看这是否能解决问题。