In Vue 3, both reactive([])
and ref([])
can be used to create a reactive array. However, the choice between them depends on your specific use case and requirements.
reactive([])
: When you usereactive([])
, you create a reactive object that wraps the array. This means that any changes made to the array, such as adding or removing elements, will trigger reactivity and update the UI accordingly. This approach is suitable when you need fine-grained reactivity and want to track changes at the array level.
Example:
import { reactive } from 'vue';
const myArray = reactive([]);
myArray.push('item 1');
console.log(myArray); // Output: ['item 1']
ref([])
: When you useref([])
, you create a reactive reference to the array. The array itself is not reactive, but you can access and modify it through the.value
property of the ref. This approach is useful when you primarily need to access the array and don't require fine-grained reactivity.
Example:
import { ref } from 'vue';
const myArray = ref([]);
myArray.value.push('item 1');
console.log(myArray.value); // Output: ['item 1']
In most cases, using reactive([])
is suitable for managing reactive arrays in Vue 3. However, if you only need simple reactivity or prefer a more explicit way to access the array, ref([])
can be a good option.