Blog>
Snippets

Watching Array Dependencies

Show how to use Vue's watchEffect to watch array dependencies and react to changes in array elements or the array length.
const { reactive, watchEffect } = Vue;

// Define a reactive Vue instance with an array
const state = reactive({
  numbers: [1, 2, 3]
});

// Use watchEffect to watch the array for reactivity
watchEffect(() => {
  // Logs the current array whenever a change is detected
  console.log('Array has changed:', state.numbers);

  // This can also react to the array's length changes
  console.log('Array length:', state.numbers.length);
});
This code snippet creates a reactive Vue instance containing an array named 'numbers'. It then utilizes Vue's 'watchEffect' method to watch the array for changes, including changes to its length. Whenever a change occurs in the array, a message with the updated array and its length will be logged to the console.
// Add an element to the reactive array and watch the effects
state.numbers.push(4);

// Remove an element from the reactive array and watch the effects
state.numbers.pop();
These two lines of code will demonstrate the reactivity of the array 'numbers' by pushing a new value to the array and then popping a value from it. Each operation will trigger the 'watchEffect' and log the updated array and its length to the console.