Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting VueJS data properties to initial values

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

like image 890
Stetzon Avatar asked Apr 26 '17 19:04

Stetzon


People also ask

How do I reset my Vue data?

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.

How do I reinitialize component Vue?

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.

How do you clear the input field after submitting Vue?

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.

What does $t mean in Vue?

Vuex is a state management pattern for vue. js. $t is the injected method from vue. js or Vue. i18n.


1 Answers

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;
  }
}
like image 148
thanksd Avatar answered Oct 18 '22 04:10

thanksd