zoukankan      html  css  js  c++  java
  • vue2.0函数(箭头函数)的this作用域

    在做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实例了.

  • 相关阅读:
    文档的几何形状和滚动
    聊聊并发——生产者消费者模式
    在JavaScript中什么时候使用==是正确的?
    HTML5使用canvas画图时,图片被自动放大模糊的问题
    获取元素的几种方式
    利用jQuery和CSS实现环形进度条
    最实用、最常用的jQuery代码片段
    表格样式
    javascript常量的定义
    null 和 undefined 的区别
  • 原文地址:https://www.cnblogs.com/stella1024/p/7598541.html
Copyright © 2011-2022 走看看