axios的this指向问题

发布时间 2023-11-10 18:30:24作者: 看热闹的蓝胖子
  let vue = new Vue({
 	 methods:{
		 testMethod:function () {
	 		//第一个: 
			axios({
			 method:"post",
			 url:"CartServlet",
			 }).then(response=>{
				this.cartJson = response;
			 });
			// 第二个:
			 axios({
			 method:"post",
			 url:"CartServlet",
			}).then(function (response) {
			   this.cartJson = response;
			});
		 }
	 }
  })

对于第一个写法,它使用了简洁的箭头函数语法,箭头函数没有自己的this指向,它会继承外层作用域的this,因此,在箭头函数内部,this.cartJson指向的是请求发起所在的Vue组件实例。

对于第二个写法,它使用了传统的匿名函数声明方式,匿名函数有自己的this指向,根据它被调用的方式不同,这个this指向也可能不同,因此,在函数内部,this.cartJson指向的不是请求发起所在Vue组件实例,而是当前匿名函数对应的this值。

如果使用第二种写法,想要指向Vue组件则需要改成下面的方式,或者使用第一种写法

  	// 第二个:
   	 axios({
	 method:"post",
	 url:"CartServlet",
   	}).then(function (response) {
	   vue.cartJson = response;
	});