Vue的methods里面不可以使用箭头函数
Vue的methods里面不可以使用箭头函数vue中的methods不可以使用箭头函数,因为this指向的不是vue实例,使用箭头函数打印this,发现是undefinedmethods: {test: () => {console.log(this); // undefined}}箭头函数没有this,this其实是外部的this,即箭头函数体内的this对象,就是定义时所在的对象,而不是
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
更多推荐
所有评论(0)