总结一下我遇到的一个纠结很久的问题。
在项目中需要用到后台的数据对前端渲染,使用到了axios,使用点击事件在页面中发送请求,在请求过程中使用的cancelToken取消请求,我在data中定义一个cancel:null,在函数中使用了this.cancel = c (赋值),会报错,
原因就是
我在普通函数里去使用this,this指向的是调用它的对象,并不是指向的vue实例
axios({
methods: 'GET',
url:'http://localhost:3000/posts',
cancelToken: new axios.CancelToken(function (c){
this.cancel = c //this指向了axios
})
}).then(response=>{
console.log(response)
this.cancel = null
})
解决方法:
使用箭头函数,不会改变this,直接使用的外面的this,也就是vue实例
axios({
methods: 'GET',
url:'http://localhost:3000/posts',
cancelToken: new axios.CancelToken( (c)=>{
this.cancel = c
})
}).then(response=>{
console.log(response)
this.cancel = null
})
真是一个小问题,可是就是得花时间去找