使用vue+elementui实现 顶部导航栏并实现动态路由
时间: 2023-09-13 21:09:58 浏览: 258
好的,实现顶部导航栏可以使用 Element UI 中的 `el-menu` 组件,具体实现步骤如下:
1. 安装 Element UI
通过 npm 安装 Element UI:
```
npm install element-ui -S
```
2. 引入 Element UI
在 `main.js` 中引入 Element UI:
```js
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
```
3. 编写顶部导航栏
```html
<template>
<div>
<el-menu mode="horizontal" :router="true">
<el-menu-item index="/">首页</el-menu-item>
<el-submenu index="/products">
<template slot="title">产品</template>
<el-menu-item index="/products/mobile">手机</el-menu-item>
<el-menu-item index="/products/computer">电脑</el-menu-item>
</el-submenu>
<el-menu-item index="/about">关于我们</el-menu-item>
</el-menu>
<router-view></router-view>
</div>
</template>
```
在 `el-menu` 中设置 `mode="horizontal"` 表示水平导航栏,设置 `:router="true"` 开启路由模式。使用 `el-menu-item` 和 `el-submenu` 分别表示菜单项和子菜单。
4. 配置动态路由
在路由配置文件中,使用 `route` 方法实现动态路由:
```js
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Products from './views/Products.vue'
import Mobile from './views/Mobile.vue'
import Computer from './views/Computer.vue'
import About from './views/About.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/products',
name: 'products',
component: Products,
children: [
{
path: 'mobile',
name: 'mobile',
component: Mobile
},
{
path: 'computer',
name: 'computer',
component: Computer
}
]
},
{
path: '/about',
name: 'about',
component: About
}
]
})
```
在 `routes` 中配置路由规则,使用 `children` 表示子路由。
这样就可以实现一个简单的带动态路由的顶部导航栏了。
阅读全文
相关推荐


















