Vue JS:data(){return {}}与data :()=>的区别({}) [英] Vue JS: Difference of data() { return {} } vs data:() => ({ })
问题描述
我很好奇这两个数据功能,两者之间是否有任何区别.
I'm curious both of this data function, is there any difference between this two.
我通常看到的是
data () {
return {
obj
}
}
我通常使用的ES6胖箭头"
And ES6 "fat arrow" which I typically used
data:()=>({
obj
})
推荐答案
在您的特定示例中没有任何区别,但是这两种表示法之间有一个非常重要的区别,尤其是在Vue方面. js: this
不会在箭头函数中反映出vue实例.
No difference in your specific example, but there is a very important difference between those two notations, specially when it comes to Vue.js: the this
won't reflect the vue instance in arrow functions.
所以,如果您有类似的东西:
So if you ever have something like:
export default {
props: ['stuffProp'],
data: () => ({
myData: 'someData',
myStuff: this.stuffProp
})
}
它不能按您预期的那样工作. this.stuffProp
不会获得stuffProp
道具的价值(有关原因,请参见下文).
It won't work as you expect. The this.stuffProp
won't get the stuffProp
prop's value (see below for more on the reason why).
将箭头功能更改为(ES6/EcmaScript 2015表示法):
Change the arrow function to, either (ES6/EcmaScript 2015 notation):
export default {
props: ['stuffProp'],
data() { // <== changed this line
return {
myData: 'someData',
myStuff: this.stuffProp
}
}
}
或(常规,ES5及更高版本,表示法):
Or to (regular, ES5 and before, notation):
export default {
props: ['stuffProp'],
data: function() { // <== changed this line
return {
myData: 'someData',
myStuff: this.stuffProp
}
}
}
原因
在声明Vue方法时不要使用箭头功能(() => {}
).他们从当前范围(可能是window
)中拾取this
,并且不会反映Vue实例.
Reason
Don't use arrow functions (() => {}
) when declaring Vue methods. They pick up the this
from the current scope (possibly window
), and will not reflect the Vue instance.
从 API文档:
请注意,您不应将箭头功能与
data
属性一起使用(例如,data: () => { return { a: this.myProp }}
).原因是箭头函数绑定了父上下文,因此this
不会是您期望的Vue实例,而this.myProp
将是未定义的.
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.
这篇关于Vue JS:data(){return {}}与data :()=>的区别({})的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!