Sometimes, we want to reset a component’s initial data in Vue.js.
In this article, we’ll look at how to reset a component’s initial data in Vue.js.
How to reset a component’s initial data in Vue.js?
To reset a component’s initial data in Vue.js, we can create a function that returns the initial data.
Then we can call the function to reset the data.
For instance, we write
<script>
const initialState = () => {
return {
modalBodyDisplay: "getUserInput",
submitButtonText: "Lookup",
addressToConfirm: null,
bestViewedByTheseBounds: null,
location: {
name: null,
},
};
};
export default {
data() {
return initialState();
},
methods: {
reset() {
Object.assign(this.$data, initialState());
},
},
};
</script>
to create the initialState function that returns an object with the initial data.
Then in data, we return the object returned by initialState to return the properties as the initial data.
Finally, in reset, we call Object.assign to merge the properties returned by initialState into this.$data to reset the reactive property values.
Conclusion
To reset a component’s initial data in Vue.js, we can create a function that returns the initial data.
Then we can call the function to reset the data.
2 replies on “How to reset a component’s initial data in Vue.js?”
Cool trick. it’s also functional in vue 3?
I like this web, tons of useful tricks & tips for JS / Vue and on a daily basis, please continue and more tips for the Vue 3 🙂
Thanks for reading.
Yes. It works the same way with Vue 3.