getData (data) {
let self = this
this.$axios.post('http://xxx.net:8092/quotes/retrieve', data).then(res => {
console.log(this) //console 输出undefined
const { r_data} = res.data
self.curRic = data
self.ricData = r_data
this.$forceUpdate()
})
},
使用this赋值curRic和ricData失败,输出this发现是undefined,明明使用的是箭头函数为什么会出现这种情况?
我换成self,发现可以赋值成功,但是template中却没有发生变化是什么原因?
第一个问题
箭头函数内的this自动指向了回调函数外层的 this 。(实际原因是箭头函数根本没有自己的 this,导致内部的 this 就是外层代码块的 this。正是因为它没有 this,所以也就不能用作构造函数。)
像这样的
this.$nextTick(()=>{
console.log(this) //指向了回调函数外层的 this
});
this.setTimeout(()=>{
console.log(this) //指向了回调函数外层的 this
},500);
然而你这样,this 输出 undefined
this.$axios.post().then(res => {
console.log(this) //console 输出undefined
});
then()
是异步的回调函数,this指向早变了。具体怎么变化的需要再研究一下。
第二个问题
页面没变化是因为你那个强制页面更新的函数还是用this调的。。
我表示质疑...
Vue methods里面的方法都是绑定实例的,方法中定义的箭头函数,this自然指向实例。
可以贴完整代码吗?