If there were a function in Vue core to reset a component's state (like this.$reset()), then it will simplify a common pattern and lead to clearer code.
This code
function getInitialData() {
return {
a: 1,
b: 2,
}
}
export default {
data: getInitialData,
methods: {
reset() {
this.$data = getInitialData()
},
submit() {
// do stuff
this.reset()
}
}
};
Would become
export default {
data() {
return {
a: 1,
b: 2,
}
}
methods: {
submit() {
// do stuff
this.$reset()
}
}
};
It might be a nice addition. This is indeed something I find myself doing regularly as well.
Until this might get into core, use this:
Vue.prototype.$reset = function () {
var data = this.$options.data()
Object.keys(data).forEach(key => {
this[key] = data[key]
})
}
I think this would be super useful, it's something i am forever doing.
Imo this is very easily done in userland, as @LinusBorg has demonstrated. On the other hand, in practice we might need small variations on how this works, e.g. only reseting part of the data to its original state (like a form object).
Overall I'm against adding such trivial convenience utilities into core - because this opens up a precedence: if A is in core, why isn't B also in there? And if we follow that we end up with an API surface bloated with tiny util functions, which I absolutely don't want to see.
Yeah that's a valid concern.
Most helpful comment
Imo this is very easily done in userland, as @LinusBorg has demonstrated. On the other hand, in practice we might need small variations on how this works, e.g. only reseting part of the data to its original state (like a form object).
Overall I'm against adding such trivial convenience utilities into core - because this opens up a precedence: if A is in core, why isn't B also in there? And if we follow that we end up with an API surface bloated with tiny util functions, which I absolutely don't want to see.