【问题标题】:Nuxt - composition api and watchersNuxt - 组合 API 和观察者
【发布时间】:2020-12-01 17:14:58
【问题描述】:

我正在尝试查看我的组件中的一些警告

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 确实在我的组件中更新 - 我看到数组已填满,但从未调用过此观察程序。

我正在使用https://composition-api.nuxtjs.org/

【问题讨论】:

    标签: vue.js vuejs2 nuxt.js vuejs3 vue-composition-api


    【解决方案1】:

    由于activeWarnings 是一个数组,您应该添加immediate:true 选项:

     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
        });
    

    但我推荐以下语法:

    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
        });
    

    【讨论】:

    • 非常感谢这项工作 - 有趣的是,托尼发布了这个 codesandbox.io/s/…,这正是我所拥有的。
    猜你喜欢
    • 1970-01-01
    • 2021-03-12
    • 2016-08-26
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多