I know vue expects data to be an function returning an object, so:
data () {
return {}
}
works, but this doesn't work:
data: () => {
}
Why doesn't it work though? aren't' they both the same functions returning an object
I know vue expects data to be an function returning an object, so:
data () {
return {}
}
works, but this doesn't work:
data: () => {
}
Why doesn't it work though? aren't' they both the same functions returning an object
That's because when you use {
in arrow functions, you begin a block, not an object.
The following would work:
data: () => ({
})
Notice the (
and )
. From MDN/Arrow Functions/Syntax:
Syntax - Advanced Syntax
// Parenthesize the body of function to return an object literal expression: params => ({foo: bar})
But, anyway, don't use these in Vue. From the 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.
You can. Consider props
. You may want to mutate a prop's value (using v-model
), which is not recommended. To achieve that functionality, the best practice is to create a internal property (e.g. internalStuff
) in your data
and initialize with the props value:
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">`
}