使用vue+elementui实现 顶部导航栏并实现动态路由
时间: 2023-09-13 10:04:08 浏览: 96
首先,你需要安装 Vue 和 Element UI
```
npm install vue
npm install element-ui
```
接下来,创建一个 Vue 组件作为顶部导航栏,例如:
```html
<template>
<div class="header">
<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>
</div>
</template>
<script>
export default {
methods: {
handleSelect(index) {
this.$router.push(index);
},
},
};
</script>
<style>
.header {
height: 60px;
line-height: 60px;
background-color: #f5f5f5;
}
</style>
```
然后,在你的主要 Vue 实例中,你需要定义你的路由和使用 `<router-view>` 显示路由组件。例如:
```html
<template>
<div>
<Header></Header>
<router-view></router-view>
</div>
</template>
<script>
import Header from "./Header.vue";
export default {
components: {
Header,
},
data() {
return {
routes: [
{
path: "/",
component: Home,
},
{
path: "/about",
component: About,
children: [
{
path: "company",
component: Company,
},
{
path: "team",
component: Team,
},
],
},
{
path: "/contact",
component: Contact,
},
],
};
},
computed: {
flattenedRoutes() {
return this.flattenRoutes(this.routes);
},
},
methods: {
flattenRoutes(routes) {
return routes.reduce((flattenedRoutes, route) => {
if (route.children) {
flattenedRoutes.push(...this.flattenRoutes(route.children));
} else {
flattenedRoutes.push(route);
}
return flattenedRoutes;
}, []);
},
},
};
</script>
```
最后,在你的路由定义中,你需要使用 `path-to-regexp` 依赖来动态生成路由。例如:
```javascript
import pathToRegexp from "path-to-regexp";
const routes = [
{
path: "/",
component: Home,
},
{
path: "/about",
component: About,
children: [
{
path: "company",
component: Company,
},
{
path: "team",
component: Team,
},
],
},
{
path: "/contact",
component: Contact,
},
];
const generatedRoutes = routes.reduce((generatedRoutes, route) => {
if (route.children) {
generatedRoutes.push(
...route.children.map((childRoute) => ({
...childRoute,
path: `${route.path}/${childRoute.path}`,
}))
);
} else {
generatedRoutes.push(route);
}
return generatedRoutes;
}, []);
const router = new VueRouter({
mode: "history",
routes: generatedRoutes.map((route) => ({
...route,
path: pathToRegexp(route.path),
})),
});
```
现在你就可以在 Vue 应用中使用这个顶部导航栏和动态路由了。
阅读全文