hid*_*dar 0 javascript vue.js arrow-functions
我知道 vue 期望 data 是一个返回对象的函数,所以:
data () {
return {}
}
Run Code Online (Sandbox Code Playgroud)
有效,但这不起作用:
data: () => {
}
Run Code Online (Sandbox Code Playgroud)
为什么它不起作用?不是'它们都是返回一个对象的相同函数
那是因为当你{在箭头函数中使用时,你开始的是一个块,而不是一个对象。
以下将起作用:
data: () => ({
})
Run Code Online (Sandbox Code Playgroud)
注意(和)。来自MDN/箭头函数/语法:
语法 - 高级语法
Run Code Online (Sandbox Code Playgroud)// Parenthesize the body of function to return an object literal expression: params => ({foo: bar})
但是,无论如何,不要在 Vue 中使用这些。来自API 文档:
请注意,您不应在
data属性(例如data: () => { return { a: this.myProp }})中使用箭头函数。原因是箭头函数绑定了父上下文,因此this不会像您期望的那样是 Vue 实例并且this.myProp将是未定义的。
更新:
每条评论:但即使采用推荐的方式,您仍然无法使用
this,那有什么意义呢?
你可以。考虑props。您可能想要改变 prop 的值(使用v-model),这是不推荐的。要实现该功能,最佳实践是internalStuff在您的内部创建一个属性(例如)data并使用 props 值进行初始化:
Vue.component('my-component', {
props: ['stuff'],
data() {
return {internalStuff: this.stuff}; // this works fine, wouldn't with arrow functions
},
template: `<input type="text" v-model="internalStuff">`
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2811 次 |
| 最近记录: |