Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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");
    ...
</script>

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

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

export default {
    data: function (){
        return initialState();
    },
    methods:{
        resetData: function (){
            Object.assign(this.$data, initialData());
        }
    }
}
</script>

But in vue 3 it does not work that way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading