Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to re-initialize the data in VueJs 2.0

Tags:

I was going through this answer on SO : Is there a proper way of resetting a component's initial data in vuejs?

However, the current method is not allowed now and VueJS prohibits changing the $data var.

As you can see here in this https://github.com/vuejs/vue/issues/2873 ( $data is not allowed to be modified. )

So if I try the above method, I am getting a VueJS warning:

[Vue warn]: Avoid replacing instance root $data. Use nested data properties instead.

Here is my JS code,

function initialState () {         return {             h2: 0,             ch4: 0,             c2h6: 0,             c2h4: 0,             c2h2: 0,             c3h8: 0,             c3h6: 0,             co: 0,             co2: 0,             o2: 0,             n2: 0,             selected: ''         }     }     export default {         name: 'something',         data () {             return initialState() // This is working fine          },         computed: {             tdcg: function () {                 // some logic here...             }         },         methods: {             resetFields: function () {                 this.$data = initialState() // --> This is what I want to achieve!             }         }     } 

So what is the correct and the easiest way of re initialising my data?

like image 949
Sankalp Singha Avatar asked Oct 31 '16 10:10

Sankalp Singha


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 data. Then we can call the function to reset the data. to create the initialState function that returns an object with the initial data.

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.


1 Answers

You can use Object.assign to iterate through all properties and assign them:

export default {     data () {         return {             h2: 0,             // other attributes...         };     },     methods: {         resetFields () {             Object.assign(this.$data, this.$options.data.call(this));         }     } } 

Here's a demo fiddle: https://jsfiddle.net/797yyvtz/


Note: I'm using this.$options.data to call the original data method again to get a fresh copy of the data. No need for a separate initialState function. The data method is the initial state function.

like image 99
Joseph Silber Avatar answered Sep 29 '22 13:09

Joseph Silber