是否可以在组件外部使用 route.meta 属性 ?
Is it possible to use route.meta property outside of the component?
我在我的项目中使用了 Vue 3,我在 Vue 组件中使用了 route.meta 属性,但是当我将它移动到 .ts 文件中时,它不再工作并且在浏览器中出现一个错误。
我的 .ts 文件:
import { useRoute } from "vue-router";
import { computed } from "vue";
const route = useRoute();
export const myfunction = computed(() => {
return route.meta.somedata;
});
浏览器错误:
Uncaught (in promise) TypeError: Cannot read property 'meta' of undefined
相同的代码在 .vue 文件中工作正常。
有没有办法在 .vue 文件之外使用 meta 属性?
我找到了解决办法,首先需要导入路由文件。
import router from "@/router/index";
然后使用路由器对象我们可以获得currentRoute.value然后访问元属性。
router.currentRoute.value.meta.someData
最终代码应如下所示:
import { computed } from "vue";
import router from "@/router/index";
export const myfunction = computed(() => {
return router.currentRoute.value.meta.someData;
});
我在我的项目中使用了 Vue 3,我在 Vue 组件中使用了 route.meta 属性,但是当我将它移动到 .ts 文件中时,它不再工作并且在浏览器中出现一个错误。
我的 .ts 文件:
import { useRoute } from "vue-router";
import { computed } from "vue";
const route = useRoute();
export const myfunction = computed(() => {
return route.meta.somedata;
});
浏览器错误:
Uncaught (in promise) TypeError: Cannot read property 'meta' of undefined
相同的代码在 .vue 文件中工作正常。 有没有办法在 .vue 文件之外使用 meta 属性?
我找到了解决办法,首先需要导入路由文件。
import router from "@/router/index";
然后使用路由器对象我们可以获得currentRoute.value然后访问元属性。
router.currentRoute.value.meta.someData
最终代码应如下所示:
import { computed } from "vue";
import router from "@/router/index";
export const myfunction = computed(() => {
return router.currentRoute.value.meta.someData;
});