What is the best way to reset a component's reactive data in vue 3?

Let’s say there is a component with multiple reactive data. How can we reset them back to the initial state?

<script setup>
    const var_a = ref("");
    const var_b = ref([]);
    const var_c = ref({});
    const var_d = ref(false);
    const var_e = ref(1);
    const var_f = ref("a");

In vue 2 we could do that by just using Object.assign() with an object and simply re/define it to data() whenever needed.

function initialData (){
  return {
    var_a: "",
    var_b: [],
    var_c: {},
    var_d: false,
    var_e: 1,
    var_f: "a",

export default {
    data: function (){
        return initialState();
        resetData: function (){
            Object.assign(this.$data, initialData());

But in vue 3 it does not work that way.

I could declare all the component data on to const state then loop trough it but it does not feel like a convenient way.

So what would be the best way to reset those on vue 3?

>Solution :

If the whole state needs to be reset, it shouldn’t be defined separately. Instead, it’s defined as reactive object:

const state = reactive(initialState());

It can be reset the same way as before:

Object.assign(state, initialState());

The state can be used separately if needed:

const { var_a } = toRefs(state);

Leave a Reply