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 state object.
For instance, we write
<script>
const initialState = () => {
return {
modalBodyDisplay: "getUserInput",
submitButtonText: "Lookup",
addressToConfirm: null,
bestViewedByTheseBounds: null,
location: {
name: null,
address: null,
position: null,
},
};
};
//...
export default {
data() {
return initialState();
},
methods: {
resetWindow() {
Object.assign(this.$data, initialState());
},
},
};
</script>
to call the initialState
function in data
to return the object returned by initialState
as the initial state values.
Then in resetWindow
, we call Object.assign(this.$data, initialState())
to overwrite the reactive properties in this.$data
with the properties in the object returned by initialState
.
Conclusion
To reset a component’s initial data in Vue.js, we can create a function that returns the initial state object.