[英]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.在我的作文 function 中,我只是推入反应阵列以模拟警告。
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?这在 Vue 2 中根本不起作用吗? Is there a workaround?有解决方法吗? activeWarnings does update in my component - I see the array filling up but this watcher is never called. activeWarnings 确实在我的组件中更新 - 我看到数组已填满,但从未调用过此观察程序。
I am using https://composition-api.nuxtjs.org/我正在使用https://composition-api.nuxtjs.org/
Since activeWarnings
is an array you should add immediate:true
option:由于activeWarnings
是一个数组,您应该添加immediate:true
选项:
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.