700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Vue踩坑—axios数据赋值错误Uncaught (in promise) TypeError: Cannot set property ‘mes‘ of undefined

Vue踩坑—axios数据赋值错误Uncaught (in promise) TypeError: Cannot set property ‘mes‘ of undefined

时间:2019-07-20 16:35:59

相关推荐

Vue踩坑—axios数据赋值错误Uncaught (in promise) TypeError: Cannot set property ‘mes‘ of undefined

最近正在入门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;})}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。