VUE的箭头函数与普通函数的区别


!!!转载出自:

***https://www.cnblogs.com/stella1024/p/7598541.html

在做vue项目时用到了axios,但是发现axios请求之后的回调函数里this并不指向当前vue实例,从而导致浏览器报错。

出错代码及结果:

  created : function(){
      axios.get('static/data.json').then(function(res){
          console.log(this)    //undefined
      this.user = res.data.user
   })
  }


普通函数代码改版(正确):


 created : function(){
      var _this = this
      axios.get('static/data.json').then(function(res){
          console.log(this)    //undefined
          console.log(_this)   //VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
      _this.user = res.data.user
   })
  }

从以上结果来看,在created下的函数this指向的是当前创建的vue实例,而在这些函数内部使用例如axios与后台交互后回调函数的内部的this并非指向当前的vue实例;
若想拿到后台回传的数据更新data里的数据,不能在回调函数中直接使用this,而要用在外部函数定义的变量存储的this,也就是当前vue的实例。

箭头函数代码改版(正确):

created : function(){
      axios.get('static/data.json').then((res) => {
          console.log(this)      //VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
      this.user = res.data.user
   })
  }

箭头函数相当于匿名函数,并且简化了函数定义。看上去是匿名函数的一种简写,但实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,由上下文确定。此时this在箭头函数中已经按照词法作用域绑定了。很明显,使用箭头函数之后,箭头函数指向的函数内部的this已经绑定了外部的vue实例了.

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值