vue el-menu实现菜单页面切换
时间: 2023-08-25 07:18:50 浏览: 159
要实现菜单页面切换,可以使用Vue.js和Element UI中的el-menu组件。
1. 首先,在Vue.js中定义一个数据对象,用来存储菜单选项和对应的页面路由:
```
data() {
return {
menuItems: [
{
index: 'home',
title: '首页',
route: '/'
},
{
index: 'about',
title: '关于我们',
route: '/about'
},
{
index: 'contact',
title: '联系我们',
route: '/contact'
}
]
}
}
```
2. 在模板中,使用el-menu组件来渲染菜单。设置mode属性为horizontal,表示菜单水平排列;设置default-active属性为当前选中的菜单项的index值:
```
<el-menu :default-active="$route.path" mode="horizontal">
<el-menu-item v-for="item in menuItems" :key="item.index" :index="item.route">{{ item.title }}</el-menu-item>
</el-menu>
```
3. 在路由配置中,定义对应的页面组件,并设置路由路径为菜单项的route值:
```
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact }
]
```
4. 最后,在页面组件中,使用Vue.js的路由功能来实现页面切换。例如,在点击菜单项时,使用this.$router.push()方法将路由切换到对应的页面:
```
methods: {
handleMenuSelect(index) {
this.$router.push(index)
}
}
```
完整代码示例:
```
<template>
<el-menu :default-active="$route.path" mode="horizontal" @select="handleMenuSelect">
<el-menu-item v-for="item in menuItems" :key="item.index" :index="item.route">{{ item.title }}</el-menu-item>
</el-menu>
</template>
<script>
import Home from './Home.vue'
import About from './About.vue'
import Contact from './Contact.vue'
export default {
data() {
return {
menuItems: [
{
index: 'home',
title: '首页',
route: '/'
},
{
index: 'about',
title: '关于我们',
route: '/about'
},
{
index: 'contact',
title: '联系我们',
route: '/contact'
}
]
}
},
methods: {
handleMenuSelect(index) {
this.$router.push(index)
}
},
components: {
Home,
About,
Contact
}
}
</script>
<style scoped>
/* 样式 */
</style>
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)