I have a component that is provided an initial data property via a passed-in component prop
and stored in a data variable:
<component :propvar="true"></component>
data() {
return {
localvar: this.propvar,
localvar2: true
}
}
I would like to be able to revert the data variable back to this prop's value when hitting a 'reset' button with a method like this:
methods: {
reset() {
Object.assign(this.$data, this.$options.data());
}
}
The problem is that the data variable is undefined
when referencing the prop's value via this.options.data()
:
console.log(this.$options.data()); => Object {localvar: undefined, localvar2: true}
Example Fiddle
I have a component that is provided an initial data property via a passed-in component prop
and stored in a data variable:
<component :propvar="true"></component>
data() {
return {
localvar: this.propvar,
localvar2: true
}
}
I would like to be able to revert the data variable back to this prop's value when hitting a 'reset' button with a method like this:
methods: {
reset() {
Object.assign(this.$data, this.$options.data());
}
}
The problem is that the data variable is undefined
when referencing the prop's value via this.options.data()
:
console.log(this.$options.data()); => Object {localvar: undefined, localvar2: true}
Example Fiddle
Share Improve this question edited Apr 26, 2017 at 20:31 thanksd 55.6k23 gold badges165 silver badges154 bronze badges asked Apr 26, 2017 at 19:49 StetzonStetzon 7392 gold badges10 silver badges19 bronze badges1 Answer
Reset to default 21If you really need to reset all of your data properties by firing the data()
method again, you can do that like so:
methods: {
reset() {
Object.assign(this.$data, this.$options.data.call(this));
}
}
The this
variable in the this.$options.data
is referencing the options, not the vue component instance. That's why the localvar
property was undefined
. So if you're calling it from the vue instance, you'll need to give it a reference to this
via the function's call()
method.
But, in most circumstances, I would just assign the value directly instead of calling Object.assign
:
methods: {
reset() {
this.localvar = this.propvar;
}
}