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?
Wrap all the data into a dict with a key called "data" or other thing. Then you can re-initialize whole data by set this.data = {xx: yy}, or directly change one data item like this.data.h2 = 2.
You can try this:
You can use
Object.assign
to iterate through all properties and assign them:Here's a demo fiddle: https://jsfiddle.net/797yyvtz/
Note: I'm using
this.$options.data
to call the originaldata
method again to get a fresh copy of the data. No need for a separateinitialState
function. Thedata
method is the initial state function.My solution:
When you need you can load or save them again
Did you try iterating through the initialState object and setting it again? Here is the sample code:
In my limited experiments locally, it does seem to work. Let me know your thoughts on this method.