How to re-initialize data in Vue.js?

Sometimes, we want to re-initialize data in Vue.js.

In this article, we’ll look at how to re-initialize data in Vue.js.

How to re-initialize data in Vue.js?

To re-initialize data in Vue.js, we can use the Object.assign method with this.$data.

For instance, we write


<script>
//...
const initialState = () => {
  return {
    h2: 0,
    ch4: 0,
    //...
  };
};
//...
export default {
  //...
  data() {
    return initialState();
  },
  methods: {
    resetFields() {
      Object.assign(this.$data, initialState());
    },
  },
  //...
};
</script>

to call Object.assign with the this.$data property and the object returned by the initialState function to reset the reactive properties to the initial values.

We use the same object returned by initialState as the initial values of the reactive properties.

Conclusion

To re-initialize data in Vue.js, we can use the Object.assign method with this.$data.