element-ui 侧边导航栏
时间: 2025-04-24 08:10:42 浏览: 29
### 使用 Element-UI 实现侧边导航栏
为了实现带有动态收缩与展开功能的侧边导航栏,可以利用 Vue 2.x 和 Element-UI 提供的功能来完成。具体来说,通过 `el-menu` 组件以及一些自定义样式和逻辑控制,能够满足需求。
#### HTML 结构
首先,在模板部分定义好基本布局:
```html
<template>
<div class="layout">
<!-- 左侧菜单 -->
<el-aside width="auto" style="background-color: rgb(50, 65, 87)">
<el-menu router :collapse="isCollapse" background-color="#545c64"
text-color="#fff" active-text-color="#ffd04b">
<!-- 动态加载菜单项 -->
<sidebar-item v-for="(item,index) in routes" :key="index" :item="item"></sidebar-item>
</el-menu>
</el-aside>
<!-- 右侧主体内容区 -->
<el-container>
...
</el-container>
</div>
</template>
```
上述代码片段中引入了 `el-aside` 来作为左侧区域,并设置了背景颜色;而内部嵌套了一个 `el-menu` 菜单组件,其中包含了几个重要属性:`router`, `collapse`, `background-color`, `text-color`, `active-text-color`. 这些属性分别用来启用路由模式、切换收起状态、指定不同状态下文字的颜色等效果[^1].
#### JavaScript 部分
接着是在脚本文件里处理业务逻辑的地方:
```javascript
<script>
export default {
name: 'Layout',
computed:{
isCollapse(){
return this.$store.getters.sidebarOpened;
},
routes() {
return this.$router.options.routes.filter(route => !route.hidden);
}
},
}
</script>
```
这里主要做了两件事:
- 计算属性 `isCollapse`: 获取 Vuex store 中存储的状态值决定是否要折叠侧边栏;
- 方法 `routes()` :过滤掉隐藏不显示于菜单中的路径并返回给视图层使用.
#### 样式调整
最后还需要适当修改 CSS 样式以适应页面设计的要求:
```css
<style scoped lang="scss">
.layout{
height: 100%;
}
.el-menu-vertical-demo:not(.el-menu--collapse){
width: 200px;
min-height: 400px;
}
// 解决element-ui中子选项长度有时会超出边框的问题
.over-hide {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
</style>
```
以上就是基于 Vue.js 和 Element-UI 构建的一个简单但完整的例子,它不仅支持常规的操作还加入了更多实用特性比如动态改变宽度大小等功能[^3].
阅读全文
相关推荐


















