Vue的methods里面不可以使用箭头函数

Vue的methods里面不可以使用箭头函数

vue中的methods不可以使用箭头函数,因为this指向的不是vue实例,使用箭头函数打印this,发现是undefined

methods: {
    test: () => {
        console.log(this); // undefined
    }
}

箭头函数没有this,this其实是外部的this,即箭头函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。所以箭头函数的this是固定的,不能改变或者重新绑定

箭头函数转成 ES5 的代码如下。

// ES6
function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

// ES5
function foo() {
  var _this = this;

  setTimeout(function () {
    console.log('id:', _this.id);
  }, 100);
}

而普通函数的this,是指向运行时所在的作用域,所以是可以改变或重新绑定

function Timer() {
  this.s1 = 0;
  this.s2 = 0;
  // 箭头函数
  setInterval(() => this.s1++, 1000);
  // 普通函数
  setInterval(function () {
    this.s2++;
  }, 1000);
}

var timer = new Timer();

setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
// s1: 3
// s2: 0

Timer函数内部设置了两个定时器,分别使用了箭头函数和普通函数。前者的this绑定定义时所在的作用域(即Timer函数),后者的this指向运行时所在的作用域(即全局对象)。所以,3100 毫秒之后,timer.s1被更新了 3 次,而timer.s2一次都没更新。

回到原来vue中methods使用箭头函数时,this为undefined的问题,查看源码

function initMethods (vm, methods) {
  var props = vm.$options.props;
  for (var key in methods) {
    if (process.env.NODE_ENV !== 'production') {
      if (typeof methods[key] !== 'function') {
        warn(
          "Method \"" + key + "\" has type \"" + (typeof methods[key]) + "\" in the component definition. " +
          "Did you reference the function correctly?",
          vm
        );
      }
      if (props && hasOwn(props, key)) {
        warn(
          ("Method \"" + key + "\" has already been defined as a prop."),
          vm
        );
      }
      if ((key in vm) && isReserved(key)) {
        warn(
          "Method \"" + key + "\" conflicts with an existing Vue instance method. " +
          "Avoid defining component methods that start with _ or $."
        );
      }
    }
    vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm);
  }
}

关键的一行

vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm);

这里会把methods上的方法都挂载到vue实例上,即this指向vue,而前面说过,箭头函数是没有this的,并且是无法改变或重新绑定的,又因为methods是一个对象,而对象不构成单独的作用域,导致箭头函数定义时的作用域是全局作用域,也就是window对象,所以vue的methods中不可以使用this。

那么问题来了,按这么说,那this应该是window对象,那为什么打印出来的是undefined呢?

原因是vue中使用的是严格模式use strict,所以this是undefined。

参考:
https://es6.ruanyifeng.com/#docs/function#%E7%AE%AD%E5%A4%B4%E5%87%BD%E6%95%B0

  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值