至少现在,这是我的解决方案:
- 在
router.js(或在我的情况下为/router/index.js)声明带有原始问题中所示标签的路线。并导出 both 路由和路由器对象。
const routes = [
{
path: '/',
name: 'home',
label: 'Start',
component: Home
}
...
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export { router as default, routes };
- 在
main.js 中导入两个变量并存储routes,以便您可以在任何地方检索它们。
import router, { routes } from '@/router'
Vue.prototype.routes = routes
new Vue({
router,
store,
vuetify,
render: h => h(App)
}).$mount('#app')
- 您想在哪里“渲染”路线链接(在我的例子中是导航栏布局),请执行以下操作(在此处使用 vuetify):
<v-app-bar app color="secondary" dark>
<v-btn v-for="route in routes" :to="{name: route.name}" key='route.name' text rounded :exact="true">
{{ route.label }}
</v-btn>
</v-app-bar>
我确信这可以通过使用 Vuex(我仍在研究)来改进。
更新
找到了一个更好的解决方案,不需要routes 导出/导入并将其分配给Vue.prototype.routes = routes。只需在要使用带有标签的路由数据的组件中执行此操作即可。模板部分(v-btn 等)保持不变。
<script>
export default {
name: 'LayoutNav',
data() {
return {
routes: this.$router.options.routes
};
}
};
</script>