Categories
Vue Answers

How to reset a component’s initial data in Vue.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

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 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *