![](/style/images/good.png)
![](/style/images/bad.png)
vue 中使用 this 更新数据的一次大坑 - luis林威
source link: https://www.cnblogs.com/luisblog/p/16919628.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
vue 中使用 this 更新数据的一次大坑
情景说明:
之前用 vue 做数据绑定更新时,发现一个莫名奇妙的问题。
我在 vue 实例中声明了一个数组属性如
books: []
,在异步请求的回调函数中使用this.books = res.data.data;
进行数据更新,更新步骤后面紧跟着打印了console.log(this.books)
,打印数据显示确实更新成功!但页面数据渲染无论是{{books.length}}
还是{{books}}
都显示没有数据!!!这就脑瓜子疼了,花了老长时间反复证明了:
this.books
数据肯定更新上去了,但它喵的{{books}}
就是不显示!敲重点:我是在 axios 的回调函数中使用的 this 更新数据!
最后想起了一个小细节,axios 异步通信的回调函数我用的是函数表达式
axios({xxx}).then(function(res){xxx})
,格式示例如下:axios({ url: url, method: "get", headers: { token: token }, //自定义请求头数据传递token params: { userId: userId } }).then(function(res) { //上面的回调函数用的标准格式 } });
使用这种格式的回调函数写法,如果在回调函数中,使用 this,那么,这个 this 就不是 vm(ViewModel) 对象了,而是回调函数自身这个对象!!!
所以,使用这种回调函数写法,在回调函数中,就不能使用类似
this.books
进行数据更新!只能使用vm.books
(vm 指的是创建 vue 实例对象时的引用或对象属性名称)来进行对 vue 对象数据的更新。如果想使用 this 来实现数据更新,那就必须使用回调函数的简写格式:
axios({xxx}).then((res)=>{xxx})
,格式示例如下:axios({ url: url, method: "get", headers: { token: token }, //自定义请求头数据传递token params: { userId: userId } }).then((res)=>{ //上面的回调函数用的简写格式 } });
使用这种简写格式的回调函数写法,就可以直接在回调函数中使用 this,此时,这个 this 也是 vm(ViewModel) 对象!!!
PS:好吧,这细节也是没谁了,也怪我自己突然没注意到,使用了标准格式的回调函数写法~
但是,话说 ,为什么它喵的,使用标准格式写法,this 指的不是 vue 实例对象,但是用它更新的数据如
this.books
也给更新上去了,打印出来也真的是一点毛病没有???
__EOF__
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK