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