Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt - composition api and watchers

I am trying to watch for some warnings in my component

import VueCompositionApi, { watch } from '@vue/composition-api';
import useWarning from '@composables/warnings';

Vue.use(VueCompositionApi);

setup () {

    const { activeWarnings } = useWarning();

     watch(activeWarnings, () => {
      
        console.log('called inside on update')
    });

    }

In my composition function I just push into the reactive array to simulate warning.

import { reactive } from '@vue/composition-api';

export default function useWarnings () {

  const activeWarnings = reactive([]);

  setInterval(() => {
    fakeWarning();
  }, 3000);


  function fakeWarning () {
    activeWarnings.push({
      type: 'severe',
      errorCode: 0,
      errorLevel: 'red',
    
    }
);
  }
 return { activeWarnings };

Does this not work in Vue 2 at all? Is there a workaround? activeWarnings does update in my component - I see the array filling up but this watcher is never called.

I am using https://composition-api.nuxtjs.org/

like image 909
AlexanderDavidson Avatar asked Dec 31 '25 08:12

AlexanderDavidson


1 Answers

Since activeWarnings is an array you should add immediate:true option :

 const { activeWarnings } = useWarning();

     watch(activeWarnings, () => {
      
        console.log('called inside on update')
    },{
     immediate:true
    });

or

 const { activeWarnings } = useWarning();

     watch(()=>activeWarnings, () => {
      
        console.log('called inside on update')
    },{
     immediate:true
    });

But i recommend the following syntax :

import { reactive,toRef } from '@vue/composition-api';

export default function useWarnings () {

  const state= reactive({activeWarnings :[]});

  setInterval(() => {
    fakeWarning();
  }, 3000);


  function fakeWarning () {
   state.activeWarnings.push({
      type: 'severe',
      errorCode: 0,
      errorLevel: 'red',
    
    }
);
  }
 return { activeWarnings : toRef(state,'activeWarnings')};

then :

 const { activeWarnings } = useWarning();

     watch(activeWarnings, () => {

        console.log('called inside on update')
    },{
     immediate:true
    });
like image 163
Boussadjra Brahim Avatar answered Jan 03 '26 22:01

Boussadjra Brahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!