簡體   English   中英

Nuxt - 無法在 watch() 回調中調用 useContext()

[英]Nuxt - Cannot call useContext() inside watch() callback

我在 Nuxt 2 中使用@nuxtjs/composition-api版本 0.33.1,我的組件如下所示:

import { defineComponent, useContext, useRoute, watch } from '@nuxtjs/composition-api';

export default defineComponent({
  setup () {
    const route = useRoute();

    // Other code...

    watch(() => route.value.query, () => {
      const { $axios } = useContext();
    });

    // Other code...
  }
});

如您所見,我正在嘗試在route.value.query更改時執行某些操作。 但是,這給了我錯誤:

Error: This must be called within a setup function.
    at useContext (index.mjs?9a99:220:1)
    at eval (search.vue?9447:34:1)
    at invokeWithErrorHandling (vue.common.dev.js?4650:3634:1)
    at call (vue.common.dev.js?4650:3271:1)
    at watcher.run (vue.common.dev.js?4650:3375:1)
    at flushSchedulerQueue (vue.common.dev.js?4650:3140:1)
    at Array.eval (vue.common.dev.js?4650:3760:1)
    at flushCallbacks (vue.common.dev.js?4650:3682:1)

我錯過了什么? 如何在watch()的回調中調用useContext() ) ? 或者根本不可能?

我在github中找到了這個答案。 該解決方案建議添加最新版本的 nuxt 組合 api。

正如 package 的開發人員所確認的那樣,在觀察者回調中不可能有useContext()

解決方法是先調用useContext() ,然后在回調中使用它的返回值。

import { defineComponent, useContext, useRoute, watch } from '@nuxtjs/composition-api';
export default defineComponent({
  setup () {
    const route = useRoute();
    // Other code...

    const { $axios } = useContext();
    watch(() => route.value.query, () => {
      // use $axios here
    });
    // Other code...
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM