最近正在入门vue,有个重要的应用场景:需要将axios请求返回的数据赋值到data中的数据项,data中的数据项会双向绑定到页面中进行渲染。
但是在回调函数中进行赋值时出现错误,原代码如下:
methods:{
tijiao(){
this.axios({
method:'post',
params:
{
yhm:this.yhm,
pwd:this.pwd
},
url:'http://localhost:1111/01/zhuce'
}).then(function(resp){
console.log(resp.data);
this.mes=resp.data;
})
}
}
当运行时会发现:数据可以请求到,但是会报错TypeError: Cannot set property ‘listgroup’ of undefined,也就是说请求到的数据无法绑定到data里的数据项。
错误原因
.then(function(resp){
console.log(resp.data);
this.mes=resp.data; //该处出错
})
then中使用了function callback,因此在回调函数里面,this是指向HTTP request event,已经不是外部的默认vue对象了。
解决办法
1、用ES6箭头函数,箭头方法可以和外部的vue对象共享变量
methods:{
tijiao(){
this.axios({
method:'post',
params:
{
yhm:this.yhm,
pwd:this.pwd
},
url:'http://localhost:1111/01/zhuce'
}).then(resp=>{ //改为箭头函数
console.log(resp.data);
this.mes=resp.data;
})
}
}
避免了函数function屏蔽了作用域。
2、使用一个 that 指向外部的this
methods:{
tijiao(){
var that=this; //使用that 指向外部的this(即vue对象)
this.axios({
method:'post',
params:
{
yhm:this.yhm,
pwd:this.pwd
},
url:'http://localhost:1111/01/zhuce'
}).then(function(resp){
console.log(resp.data);
this.mes=resp.data;
})
}
}
本文介绍在Vue中使用Axios请求数据并将其绑定到data属性时遇到的问题及解决方案,包括使用箭头函数和通过that引用外部this的方法。

被折叠的 条评论
为什么被折叠?



