vue 挂载路由到头部导航的方法(2)
这个时候浏览器中是这样的

样子很丑,但这不是重点,我们点击导航的时候,他直接跳到的是
<el-menu-item index="2-1">xxxxxx<el-menu-item>,这里面的index,所以最笨的办法就是改index的值就行了,但这样就不够灵活了....
一般写导航的办法是这样的
<template>
<el-row>
<!-- 左边logo -->
<el-col :span="4" class="logo">
<img src="../assets/logo.png" alt="">
</el-col>
<!-- 中间导航区域 -->
<el-col :span="16">
<el-menu
:default-active="$route.path"
class="menu"
router
mode="horizontal"
@select="handleSelect"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b">
<!-- 循环写的路由,其中路由中有 hidden:true 的就不加入循环 -->
<template
v-for="route in $router.options.routes"
v-if="!route.hidden">
<!-- 循环没有children的路由 -->
<el-menu-item
v-if="!route.hasChild"
:key="route.path"
:index="route.path" >
{{ route.name }}
</el-menu-item>
<!-- 循环有children的路由 -->
<el-submenu v-else :index="route.path">
<template slot="title">{{ route.name }}</template>
<el-menu-item
v-for="child in route.children"
:index="child.path"
:key="child.path">
{{ child.name }}
</el-menu-item>
</el-submenu>
</template>
</el-menu>
</el-col>
<!-- 右边用户信息以及登陆注册 -->
<el-button-group>
<el-button type="danger" size="small" round >login</el-button>
<el-button type="success" size="small" round >regin</el-button>
</el-button-group>
</el-row>
</template>
<script>
export default {
// ...
methods: {
handleSelect () {
console.log('菜单选择之后的回调操作')
}
}
}
</script>
<style scoped>
</style>
这样在浏览器中的效果



这样点击导航菜单之后的跳转就完全正常了,这样写的好处就是很灵活,如果要加icon图标的话,也可以直接在router/index.js里面的配置路由部分加个字段class:classname,然后在循环的时候输出就可以了。当然这里一般是不把首页这个导航菜单显示出来的,我们可以直接在路由配置中加个hidden:true 就实现了
