在VueJs 2.0中重新初始化数据的正确方法 [英] Proper way to re-initialize the data in VueJs 2.0
问题描述
我在SO上找到了这个答案:是否有正确的方法在vuejs中重置组件的初始数据?
I was going through this answer on SO : Is there a proper way of resetting a component's initial data in vuejs?
但是,现在不允许使用当前方法和VueJS禁止更改$ data var。
However, the current method is not allowed now and VueJS prohibits changing the $data var.
正如您在此处所见 https://github.com/vuejs/vue/issues/2873 (不允许修改$ data。)
As you can see here in this https://github.com/vuejs/vue/issues/2873 ( $data is not allowed to be modified. )
因此,如果我尝试上述方法,我会收到VueJS警告:
So if I try the above method, I am getting a VueJS warning:
[Vue警告]:避免替换实例根$ data。使用嵌套数据
属性。
[Vue warn]: Avoid replacing instance root $data. Use nested data properties instead.
这是我的JS代码,
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?
推荐答案
您可以使用 Object.assign
迭代所有属性并分配它们:
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));
}
}
}
这是一个演示小提琴:< a href =https://jsfiddle.net/797yyvtz/\"rel =noreferrer> https://jsfiddle.net/797yyvtz/
Here's a demo fiddle: https://jsfiddle.net/797yyvtz/
注意:我正在使用这个。$ options.data
来调用原来的 data
方法再次获取数据的新副本。无需单独的 initialState
函数。 数据
方法是初始状态函数。
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.
这篇关于在VueJs 2.0中重新初始化数据的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!