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.