在 VueJs 2.0 中重新初始化数据的正确方法 [英] Proper way to re-initialize the data in VueJs 2.0
问题描述
我正在解决这个问题的答案: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 变量.
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));
}
}
}
这是一个演示小提琴:https://jsfiddle.net/797yyvtz/
注意:我正在使用 this.$options.data
再次调用原始的 data
方法以获取新的数据.不需要单独的 initialState
函数.data
方法是初始状态函数.
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屋!