Vue的this指针问题,Vue使用axios的回调函数中this为undefined解决方法

[ 2022-05-03 16:16:13 | 作者: admin ]
字号: | |
在vue较多使用的是axios请求,请求后的回调函数中,this不能指向当前vue实例,打印出来是undefined;

1,let that = this,常用的存储this的方法,定义一个全局变量把this存储下来。
getSerTime:function(){
         //存储this指针,防止this在第三方组件中改变指向。也有同学喜欢 let _this = this;
         let that = this ;
         Vue.axios.get(root + '/api/findInfoDetail').then((response) => {
                console.log(response.data);
                console.log(this);
                console.log(that);
         })
}



2.使用箭头函数
//箭头函数内部的this是词法作用域,是由外层调用者vue来确定,使用箭头函数之后,箭头函数指向的函数内部的this已经绑定了外部的vue实例
Vue.axios.get(root +'/api/findInfoDetail',{params:{notid:this.searchData.notId,type:this.searchData.type}})
.then((response) => {
         console.log(response.data);
         console.log(this);
})


attachments/202205/03_162254_015f3a8ac93a4060ab18a65a6fa437ff.png



参考:
https://blog.csdn.net/m0_37885651/article/details/81558623
https://blog.csdn.net/m0_56522868/article/details/120917143
[最后修改由 admin, 于 2022-05-03 23:31:02]
评论Feed 评论Feed: http://blog.xg98.com/feed.asp?q=comment&id=2846

这篇日志没有评论。

此日志不可发表评论。