Blog>
Snippets

Conditional Reactive Effects

Create a reactive effect with Vue's watchEffect that only runs when certain conditions are met.
const { reactive, watchEffect } = Vue;

// Define a reactive state object
const state = reactive({
  count: 0,
  shouldWatch: true
});

// Define the reactive effect
watchEffect(() => {
  if (state.shouldWatch) {
    console.log(`The count is: ${state.count}`);
  }
});
This code snippet defines a reactive state object with Vue's reactive API, containing both the value to watch ('count') and the condition ('shouldWatch'). It then sets up a reactive effect with watchEffect, which only logs the count to the console if 'shouldWatch' is true.