[英]Nuxt - Cannot call useContext() inside watch() callback
I'm using @nuxtjs/composition-api
version 0.33.1 with Nuxt 2, and my component looks like this:我在 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...
}
});
As you can see, I'm trying to do something when the route.value.query
changes.如您所见,我正在尝试在
route.value.query
更改时执行某些操作。 However, this gives me the error:但是,这给了我错误:
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)
Did I miss something?我错过了什么? How can I call
useContext()
inside the callback of watch()
?如何在
watch()
的回调中调用useContext()
) ? Or is it not possible at all?或者根本不可能?
As confirmed by the developer of the package, it is not possible to have useContext()
in the watcher callback.正如 package 的开发人员所确认的那样,在观察者回调中不可能有
useContext()
。
The workaround is to call useContext()
first, then use its returned values in the callback.解决方法是先调用
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.