对vuejs-templates webpack-简单代码片段的困惑
Confused about vuejs-templates webpack-simple code snippet
我是javascript的新手。
通过阅读示例开始学习Vue.js。
但是我对vuejs-templates/webpack-simple的代码片段感到困惑。
来自line 25
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
我在想为什么代码不能这样写
data: () => {
return {
msg: 'Welcome to Your Vue.js App'
}
}
两种代码我都试过了,结果一样。
阅读 Vue.js 文档无法理解。
请帮助我理解这段代码。
感谢您花时间阅读我的问题。
问题不在于为什么不是,而是为什么要。
在这两种情况下,您都定义了一个函数,它是对象文字的成员。在 es6
中有 method properties, which is used as a shorthand notation. See also MDN.
的特征
我建议您在方法属性上使用箭头函数时要小心。
箭头函数提供词法 this
所以有时你会发现 this
没有引用正确的上下文(它应该是 Vue 对象本身,但它指向父对象,在你的情况下可能 window).
VueJS 文档给出了完全相同的警告:
Don’t use arrow functions on an instance property or callback (e.g.
vm.$watch('a', newVal => this.myMethod())). As arrow functions are
bound to the parent context, this will not be the Vue instance as
you’d expect and this.myMethod will be undefined.
https://vuejs.org/v2/guide/instance.html#Properties-and-Methods
我是javascript的新手。
通过阅读示例开始学习Vue.js。
但是我对vuejs-templates/webpack-simple的代码片段感到困惑。
来自line 25
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
我在想为什么代码不能这样写
data: () => {
return {
msg: 'Welcome to Your Vue.js App'
}
}
两种代码我都试过了,结果一样。
阅读 Vue.js 文档无法理解。
请帮助我理解这段代码。
感谢您花时间阅读我的问题。
问题不在于为什么不是,而是为什么要。
在这两种情况下,您都定义了一个函数,它是对象文字的成员。在 es6
中有 method properties, which is used as a shorthand notation. See also MDN.
我建议您在方法属性上使用箭头函数时要小心。
箭头函数提供词法 this
所以有时你会发现 this
没有引用正确的上下文(它应该是 Vue 对象本身,但它指向父对象,在你的情况下可能 window).
VueJS 文档给出了完全相同的警告:
Don’t use arrow functions on an instance property or callback (e.g. vm.$watch('a', newVal => this.myMethod())). As arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect and this.myMethod will be undefined.
https://vuejs.org/v2/guide/instance.html#Properties-and-Methods