Search code examples
vue.jsvuejs3vue-composition-apivue-reactivityvue-script-setup

How do I clear a reactive array in Vue3 using composition?


I have the following in my project...

const basicRecords = reactive([]);

It basically just houses an array of objects. I want to be able to refresh this array, that would require me to remove all of the records and add them back. To do this I have done the following...

basicRecords.splice(0);
basicRecords.push(...recordResult.data);

This seems to work but also seems super hacky.

What is the proper way to reset a reactive array in Vue3?


Solution

  • Try to use Object.assign to keep it reactive :

    const basicRecords = reactive([]);
    
    Object.assign(basicRecords, recordResult.data)
    

    or define basicRecords as inner field of reactive state :

    const state = reactive({basicRecords : []});
    
    state.basicRecords = recordResult.data
    

    or with ref :

    const basicRecords = ref([]);
    
    basicRecords.value = recordResult.data