Vue 实例上的箭头方法¶
ID: js/vue/arrow-method-on-vue-instance
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- reliability
- frameworks/vue
Query suites:
- javascript-security-and-quality.qls
Vue 框架使用实例作为接收器来调用 Vue 实例的方法。但是,对于箭头函数,无法执行实例和接收器的这种绑定,因此 Vue 实例上箭头函数中的 this
变量可能没有程序员预期的值。
建议¶
确保 Vue 实例上的方法可以将其接收器绑定到实例。
示例¶
以下示例展示了两个相似的 Vue 实例,唯一的区别是 created
生命周期钩子回调的定义方式。第一个 Vue 实例使用箭头函数作为回调。这意味着 this
变量的值将是全局对象,导致 this.myProperty
评估为 undefined
,这可能不是预期结果。相反,第二个 Vue 实例使用普通函数作为回调,导致 this.myProperty
评估为 42
。
new Vue({
data: {
myProperty: 42
},
created: () => {
// BAD: prints: "myProperty is: undefined"
console.log('myProperty is: ' + this.myProperty);
}
});
new Vue({
data: {
myProperty: 42
},
created: function () {
// GOOD: prints: "myProperty is: 1"
console.log('myProperty is: ' + this.myProperty);
}
});
参考资料¶
Vue 文档:Vue 实例