elementui 实现响应式导航
时间: 2023-09-24 14:09:56 浏览: 90
element-ui 实现响应式导航栏的示例代码
ElementUI是一款基于Vue.js的UI框架,提供了丰富的组件,包括导航组件。ElementUI的导航组件可以通过CSS媒体查询实现响应式导航。
1. 使用el-menu组件创建导航菜单
```
<el-menu :default-active="$route.path" class="el-menu-demo" mode="horizontal" :router="true">
<el-menu-item index="/">
<i class="el-icon-house"></i>
<span>首页</span>
</el-menu-item>
<el-submenu index="1">
<template slot="title">
<i class="el-icon-menu"></i>
<span>菜单</span>
</template>
<el-menu-item index="/menu1">
<span>菜单1</span>
</el-menu-item>
<el-menu-item index="/menu2">
<span>菜单2</span>
</el-menu-item>
</el-submenu>
<el-menu-item index="/about">
<i class="el-icon-info"></i>
<span>关于我们</span>
</el-menu-item>
</el-menu>
```
2. 使用CSS媒体查询实现响应式导航
在CSS中使用@media查询,根据视口的宽度调整导航菜单的样式。当视口宽度小于768px时,将使用el-dropdown组件和el-dropdown-menu组件替换el-menu和el-submenu组件。
```
@media screen and (max-width: 768px) {
.el-menu-demo {
display: none;
}
.el-dropdown-demo {
display: block;
}
}
```
替换后的代码如下:
```
<el-dropdown class="el-dropdown-demo" trigger="click">
<i class="el-icon-menu"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item index="/">
<i class="el-icon-house"></i>
<span>首页</span>
</el-dropdown-item>
<el-dropdown-item index="/menu1">
<span>菜单1</span>
</el-dropdown-item>
<el-dropdown-item index="/menu2">
<span>菜单2</span>
</el-dropdown-item>
<el-dropdown-item index="/about">
<i class="el-icon-info"></i>
<span>关于我们</span>
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
```
完整代码如下:
```
<template>
<div>
<el-menu :default-active="$route.path" class="el-menu-demo" mode="horizontal" :router="true">
<el-menu-item index="/">
<i class="el-icon-house"></i>
<span>首页</span>
</el-menu-item>
<el-submenu index="1">
<template slot="title">
<i class="el-icon-menu"></i>
<span>菜单</span>
</template>
<el-menu-item index="/menu1">
<span>菜单1</span>
</el-menu-item>
<el-menu-item index="/menu2">
<span>菜单2</span>
</el-menu-item>
</el-submenu>
<el-menu-item index="/about">
<i class="el-icon-info"></i>
<span>关于我们</span>
</el-menu-item>
</el-menu>
<el-dropdown class="el-dropdown-demo" trigger="click">
<i class="el-icon-menu"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item index="/">
<i class="el-icon-house"></i>
<span>首页</span>
</el-dropdown-item>
<el-dropdown-item index="/menu1">
<span>菜单1</span>
</el-dropdown-item>
<el-dropdown-item index="/menu2">
<span>菜单2</span>
</el-dropdown-item>
<el-dropdown-item index="/about">
<i class="el-icon-info"></i>
<span>关于我们</span>
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</div>
</template>
<script>
export default {
name: 'ResponsiveNav',
data() {
return {};
}
};
</script>
<style scoped>
@media screen and (max-width: 768px) {
.el-menu-demo {
display: none;
}
.el-dropdown-demo {
display: block;
}
}
</style>
```
以上就是使用ElementUI实现响应式导航的方法。
阅读全文