vue.js - Vue methods 用箭头函数取不到 this
本文介绍了vue.js - 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;
这篇关于vue.js - Vue methods 用箭头函数取不到 this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文