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
To reset a component's initial data in Vue. js, we can create a function that returns the initial state object. to call the initialState function in data to return the object returned by initialState as the initial state values. Then in resetWindow , we call Object.
The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.
In vue. js, we use the v-model directive to create a two-way data binding between the input field and vue data property, so that we can clear an input field value by setting the empty string (" ") to the data property.
Vuex is a state management pattern for vue. js. $t is the injected method from vue. js or Vue. i18n.
If 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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With