使用vue+elementui实现 顶部导航栏并实现动态路由
时间: 2023-12-26 16:03:52 浏览: 162
首先,在Vue项目中安装ElementUI,可以使用npm命令:
```
npm install element-ui --save
```
然后在main.js中引入并使用ElementUI:
```javascript
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App.vue'
import router from './router'
Vue.use(ElementUI)
new Vue({
router,
render: h => h(App),
}).$mount('#app')
```
接下来,我们可以在App.vue中添加顶部导航栏,结合ElementUI的el-menu组件实现:
```html
<template>
<div>
<el-menu :default-active="$route.path" mode="horizontal" @select="handleSelect">
<el-menu-item index="/">首页</el-menu-item>
<el-submenu index="/about">
<template slot="title">关于我们</template>
<el-menu-item index="/about/company">公司简介</el-menu-item>
<el-menu-item index="/about/team">团队介绍</el-menu-item>
</el-submenu>
<el-menu-item index="/contact">联系我们</el-menu-item>
</el-menu>
<router-view/>
</div>
</template>
<script>
export default {
methods: {
handleSelect(key, keyPath) {
this.$router.push(key)
}
}
}
</script>
```
然后,在router.js中定义路由,并将其动态添加至el-menu中:
```javascript
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
Vue.use(Router)
const routes = [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: () => import('./views/About.vue'),
redirect: '/about/company',
children: [
{
path: 'company',
name: 'company',
component: () => import('./views/Company.vue')
},
{
path: 'team',
name: 'team',
component: () => import('./views/Team.vue')
}
]
},
{
path: '/contact',
name: 'contact',
component: () => import('./views/Contact.vue')
}
]
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes
})
router.beforeEach((to, from, next) => {
document.title = to.meta.title || 'My Website'
next()
})
export default router
```
在这里,我们实现了顶部导航栏和动态路由。当用户点击菜单项时,会通过handleSelect方法来更新路由路径,然后通过vue-router来渲染对应的组件。
阅读全文