Vue.js Nuxt-组合api和观察程序
我试图在我的组件中观察一些警告Vue.js Nuxt-组合api和观察程序,vue.js,vuejs2,nuxt.js,vuejs3,vue-composition-api,Vue.js,Vuejs2,Nuxt.js,Vuejs3,Vue Composition Api,我试图在我的组件中观察一些警告 import VueCompositionApi, { watch } from '@vue/composition-api'; import useWarning from '@composables/warnings'; Vue.use(VueCompositionApi); setup () { const { activeWarnings } = useWarning(); watch(activeWarnings, () =&g
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')
});
}
在合成函数中,我只是将其推入反应数组以模拟警告
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 };
这在Vue 2中根本不起作用吗?有解决办法吗?activeWarnings确实会在我的组件中更新-我看到阵列已满,但从未调用过此监视程序
我使用的是,因为
activeWarnings
是一个数组,您应该添加immediate:true
选项:
const { activeWarnings } = useWarning();
watch(activeWarnings, () => {
console.log('called inside on update')
},{
immediate:true
});
或
但我建议使用以下语法:
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')};
然后:
const { activeWarnings } = useWarning();
watch(activeWarnings, () => {
console.log('called inside on update')
},{
immediate:true
});
非常感谢这项工作——有趣的是,托尼发布了这篇文章,这正是我所拥有的。不客气!
const { activeWarnings } = useWarning();
watch(activeWarnings, () => {
console.log('called inside on update')
},{
immediate:true
});