Reputation: 1043
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/
Upvotes: 3
Views: 3485
Reputation: 1
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
});
Upvotes: 2