San*_*gha 23 javascript vue.js vue-component
我在SO上回答这个问题:是否有正确的方法在vuejs中重置组件的初始数据?
但是,现在不允许使用当前方法,VueJS禁止更改$ data var.
正如您在此https://github.com/vuejs/vue/issues/2873中所见($ data不允许修改.)
所以如果我尝试上面的方法,我会得到一个VueJS警告:
[Vue警告]:避免替换实例根$ data.请改用嵌套数据属性.
这是我的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!
}
}
}
Run Code Online (Sandbox Code Playgroud)
那么重新初始化数据的正确和最简单的方法是什么?
Jos*_*ber 39
您可以使用Object.assign迭代所有属性并分配它们:
export default {
data () {
return {
h2: 0,
// other attributes...
};
},
methods: {
resetFields () {
Object.assign(this.$data, this.$options.data.call(this));
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个演示小提琴:https://jsfiddle.net/797yyvtz/
注意:我正在使用this.$options.data再次调用原始data方法来获取数据的新副本.无需单独的initialState功能.该data方法是初始状态函数.
您是否尝试迭代初始状态对象并再次设置它?这是示例代码:
function initialState() {
return {
h2: 0,
ch4: 0,
// and so on... finally
selected: ''
}
}
export default {
name: 'something',
data: function() {
return initialState()
},
computed: {
// ...
},
methods: {
resetFields: function() {
// Fetch the initialState object locally, so we do not have to call the function again
let initialData = initialState();
// Iterate through the props
for (let prop in initialData) {
// Reset the prop locally.
this[prop] = initialData[prop];
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我本地有限的实验中,它似乎确实有效。让我知道您对此方法的想法。