how to use addRoute inside router.beforeEach ? #2003
-
Here is my code using for adding route dynamically, but it only works when I use outside router.beforeEach. import { createRouter, createWebHistory } from 'vue-router';
import CreateAuthor from '@/views/cms/author/Create.vue';
import { useModuleStore } from '@/stores/com/system';
import { computed, ref } from 'vue';
const routeToComponentMap = {
'cms': CreateAuthor,
}
// Tạo router instance
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [],
});
router.beforeEach(async (to, from, next) => {
const store = useModuleStore();
try {
await store.fetchTreeBySite(1);
const modules = computed(() => store.currentModuleTree)
const routesData = modules.value;
routesData.forEach(routeData => {
if(routeData.route) {
const componentImport = routeToComponentMap[String(routeData?.route)];
console.log(componentImport)
if (componentImport) {
router.addRoute({
path: `/${routeData.route}`,
component: CreateAuthor,
});
}
}
});
} catch (error) {
console.error('Error fetching data from API:', error);
}
next();
});
export default router; |
Beta Was this translation helpful? Give feedback.
Answered by
posva
Sep 29, 2023
Replies: 1 comment 1 reply
-
You need to navigate again after adding routes: https://router.vuejs.org/guide/advanced/dynamic-routing.html#Adding-Routes-inside-navigation-guards BTW: you should remove the computed from the guard, just read the value directly. It might create a leak otherwise |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
posva
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need to navigate again after adding routes: https://router.vuejs.org/guide/advanced/dynamic-routing.html#Adding-Routes-inside-navigation-guards
BTW: you should remove the computed from the guard, just read the value directly. It might create a leak otherwise