https://segmentfault.com/q/1010000007225390
Vue methods 用箭头函数取不到 this
const App = new Vue({ el: 'body', methods: { foo: () => { console.log(this) // undefined } } })
const App = new Vue({ el: 'body', methods: { foo () { console.log(this) // Vue instance } } })
对 Vue 不熟,请教一下各位大神这是什么原因
解释:
首先,看文档 http://cn.vuejs.org/api/#methods
实例方法。实例可以直接访问这些方法,也可以用在指令表达式内。方法的 this 自动绑定到实例。
在vue的methods的this是自动绑定的
然后见代码:https://github.com/vuejs/vue/...
function initMethods (vm: Component) { const methods = vm.$options.methods if (methods) { for (const key in methods) { vm[key] = methods[key] == null ? noop : bind(methods[key], vm) if (process.env.NODE_ENV !== 'production' && methods[key] == null) { warn( `method "${key}" has an undefined value in the component definition. ` + `Did you reference the function correctly?`, vm ) } } } }
你用箭头函数,会返回一个绑定当前执行上下文中的this,而且这个this,不可再切换更改了。你此处绑定的 this 是当前函数体内的this,严格模式下为undefined;
methods
-
类型:
{ [key: string]: Function }
-
详细:
methods 将被混入到 Vue 实例中。可以直接通过 VM 实例访问这些方法,或者在指令表达式中使用。方法中的
this
自动绑定为 Vue 实例。注意,不应该使用箭头函数来定义 method 函数 (例如
plus: () => this.a++
)。理由是箭头函数绑定了父级作用域的上下文,所以this
将不会按照期望指向 Vue 实例,this.a
将是 undefined。 -
示例:
var vm = new Vue({ data: { a: 1 }, methods: { plus: function () { this.a++ } } }) vm.plus() vm.a // 2