How to make dynamic routes on the vue router?
My MainNavBar component like this :
<template>
...
<v-list-item
v-for="(item, index) in listMenu"
:key="index"
@click="goTo(item)"
>
<v-list-item-content>
<v-list-item-title>{{ item }}</v-list-item-title>
</v-list-item-content>
</v-list-item>
...
</template>
<script>
export default {
...
methods: {
goTo(key) {
this.$router.push({ name: key });
},
...mapActions("dataStore", ["getMenu"])
},
computed: {
...mapGetters("dataStore", ["listMenu"])
}
};
</script>
listMenu taken from API. It is a menu list
My router configuration like this :
import Vue from "vue";
import Router from "vue-router";
import Application from "@/pages/Application"
import MainNavbar from "@/layout/MainNavbar";
...
import { APPLICATION_ROUTE as RouteConfig } from "./route-config";
Vue.use(Router);
export default new Router({
mode: 'history',
routes: [
{
path: "/menu-first",
name: RouteConfig.APPLICATION_NAME_1.NAME,
components: { default: Application, header: MainNavbar }
},
{
path: "/menu-two",
name: RouteConfig.APPLICATION_NAME_2.NAME,
components: { default: Application, header: MainNavbar }
},
...
]
});
My RouterConfig like this :
export const APPLICATION_ROUTE = {
APPLICATION_NAME_1: {
NAME: "menu-first"
},
APPLICATION_NAME_2: {
NAME: "menu-two"
},
...
};
And my application component like this :
<template>
<v-flex xs12>
<v-card dark color="light-blue darken-4">
<v-card-title>
<v-flex xs4>
<p class="title">Name</p>
<p class="body-2 margin-sub-text">{{detailMenu.name}}</p>
</v-flex>
<v-flex xs4>
<p class="title">URL</p>
<p class="body-2 margin-sub-text">{{detailMenu.url}}</p>
</v-flex>
<v-flex xs4>
...
</v-flex>
</v-card-title>
</v-card>
</v-flex>
</template>
<script>
import { mapActions, mapState, mapGetters } from "vuex";
export default {
..
created() {
this.getDetailMenu(this.$route.path);
},
computed: mapState({
data: state => state.dataStore.data,
...mapGetters("dataStore", ["detailMenu"])
}),
methods: {
...mapActions("dataStore", ["getDetailMenu"]),
},
watch: {
$route() {
this.getDetailMenu(this.$route.path);
}
}
};
</script>
From the configuration router, my router is not dynamic. I want to make my router dynamic. So the path in the router configuration is taken from listMenu (API)
How do I do that?
I suppose getDetailMenu
is calling API method to get listMenu
.
You can create route dynamically using addRoutes method
Pseudo code
created() {
this.getDetailMenu(this.$route.path)
.then((listMenu) => {
// you need to return listMenu from getDetailMenu
listMenu.forEach((item, index) => createAndAppendRoute(item, index))
})
},
methods: {
createAndAppendRoute: (item, index) => {
console.log(item, index)
// Base on your data, you should be able to create router name and path from item and index
// here is just an example
let newRoute = {
path: `/${item}`,
name: `${item}_${index}`,
components: { default: Application, header: MainNavbar },
}
this.$router.addRoutes([newRoute])
}
}