调用挂载函数后如何更新组件数据?
How to update component data after calling mounted function?
我正在尝试在调用 API(从挂载函数调用方法)后更新组件的数据
axios.get("getInfo")
.then(function(res){
this.result = res.data.result
}).catch(function(err){
console.log(err)
})
但是 "this.result = res.data.result" 没有执行,但是当我在调用之前粘贴同一行时,我得到了更新的结果(比如 this.data.result = 20)。另外,当我尝试 console.log(res.data) 时,我没有得到任何回应
我还在控制台上收到请求已完成的消息
XHR finished loading: GET "http://app/getInfo".
我的挂载函数是这样的
mounted:function(){
this.setData()
},
methods:{
setData:function(){
console.log(this.pullData())
},
}
我做错了什么?提前致谢
您需要先将对组件的引用存储在变量中,然后在函数中使用变量而不是this关键字来引用它;原因是你在 then
中创建了一个新函数,因此 this
引用了该函数而不是 Vue 组件:
var ref = this;
axios.get("getInfo")
.then(function(res){
ref.result = res.data.result
// ^^^ ref instead of this
}).catch(function(err){
console.log(err)
})
另一种更直接的方法是使用没有 this
上下文的箭头函数:
axios.get("getInfo").then(res => { // arrow function instead of anonymous function
this.result = res.data.result
}).catch(err => {
console.log(err)
})
我正在尝试在调用 API(从挂载函数调用方法)后更新组件的数据
axios.get("getInfo")
.then(function(res){
this.result = res.data.result
}).catch(function(err){
console.log(err)
})
但是 "this.result = res.data.result" 没有执行,但是当我在调用之前粘贴同一行时,我得到了更新的结果(比如 this.data.result = 20)。另外,当我尝试 console.log(res.data) 时,我没有得到任何回应
我还在控制台上收到请求已完成的消息
XHR finished loading: GET "http://app/getInfo".
我的挂载函数是这样的
mounted:function(){
this.setData()
},
methods:{
setData:function(){
console.log(this.pullData())
},
}
我做错了什么?提前致谢
您需要先将对组件的引用存储在变量中,然后在函数中使用变量而不是this关键字来引用它;原因是你在 then
中创建了一个新函数,因此 this
引用了该函数而不是 Vue 组件:
var ref = this;
axios.get("getInfo")
.then(function(res){
ref.result = res.data.result
// ^^^ ref instead of this
}).catch(function(err){
console.log(err)
})
另一种更直接的方法是使用没有 this
上下文的箭头函数:
axios.get("getInfo").then(res => { // arrow function instead of anonymous function
this.result = res.data.result
}).catch(err => {
console.log(err)
})