我很好奇这两个数据函数,这两者之间有什么区别吗?
我平时看到的是
data () {
return {
obj
}
}
还有我通常使用的 ES6 胖箭头 (=>
)
data:()=>({
obj
})
最佳答案
在你的具体例子中没有区别,但是这两个符号之间有一个非常重要的区别,特别是当涉及到 Vue.js 时:this
不会在箭头函数中反射(reflect) vue 实例。
所以如果你有这样的事情:
export default {
props: ['stuffProp'],
data: () => ({
myData: 'someData',
myStuff: this.stuffProp
})
}
它不会像您预期的那样工作。 this.stuffProp
不会获得 stuffProp
属性的值(请参阅下文了解更多原因)。
修复
将箭头函数更改为,或者(ES6/EcmaScript 2015 表示法):
export default {
props: ['stuffProp'],
data() { // <== changed this line
return {
myData: 'someData',
myStuff: this.stuffProp
}
}
}
Or to(常规,ES5 及之前,表示法):
export default {
props: ['stuffProp'],
data: function() { // <== changed this line
return {
myData: 'someData',
myStuff: this.stuffProp
}
}
}
原因
在声明 Vue 方法时不要使用箭头函数 (() => {}
)。他们从当前范围(可能是 window
)中获取 this
,并且不会反射(reflect) Vue 实例。
来自API Docs :
Note that you should not use an arrow function with the
data
property (e.g.data: () => { return { a: this.myProp }}
). The reason is arrow functions bind the parent context, sothis
will not be the Vue instance as you expect andthis.myProp
will be undefined.
关于javascript - VueJS : Difference of data() { return {} } vs data:() => ({ }),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48980865/