- 通过按钮控制侧边栏的展开和折叠
- 通过窗口宽度的变化控制侧边栏的展开和折叠(小于768px,自动折叠)
通过按钮控制展开
通过按钮控制折叠
切换到手机模式自动折叠
环境准备:Vue3+Element-UI Plus
<script setup>
import {onMounted, ref, watch} from "vue";
// 是否折叠菜单
const isCollapse = ref(false)
// 检查窗口宽度,设置侧边栏宽度
function checkClientWidth(){
console.log(document.body.clientWidth)
if (document.body.clientWidth < 768) {
document.querySelector('.el-aside').style.width = 'auto'
isCollapse.value = true
} else {
// el-aside的宽度展开要慢于el-menu
setTimeout(() => {
document.querySelector('.el-aside').style.width = '200px'
}, 300)
isCollapse.value = false
}
}
// 监听窗口变化,窗口宽度小于 768px 时,侧边栏会自动收起
window.addEventListener('resize', checkClientWidth)
// 监听点击折叠和展开图片时的变化
watch(isCollapse, (newValue)=>{
if (newValue) {
document.querySelector('.el-aside').style.width = 'auto'
} else {
// el-aside的宽度展开要慢于el-menu
setTimeout(() => {
document.querySelector('.el-aside').style.width = '200px'
}, 300)
}
})
onMounted(()=>{
// 页面刷新时,检查窗口宽度,设置侧边栏宽度
checkClientWidth()
})
</script>
<template>
<div class="common-layout">
<el-container>
<el-aside>
<el-menu
:collapse="isCollapse"
active-text-color="#ffd04b"
background-color="#545c64"
class="el-menu-vertical-demo"
default-active="2"
text-color="#fff"
>
<el-sub-menu index="1">
<template #title>
<el-icon>
<location/>
</el-icon>
<span>Navigator One</span>
</template>
<el-menu-item-group title="Group One">
<el-menu-item index="1-1">item one</el-menu-item>
<el-menu-item index="1-2">item two</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group Two">
<el-menu-item index="1-3">item three</el-menu-item>
</el-menu-item-group>
<el-sub-menu index="1-4">
<template #title>item four</template>
<el-menu-item index="1-4-1">item one</el-menu-item>
</el-sub-menu>
</el-sub-menu>
<el-menu-item index="2">
<el-icon>
<icon-menu/>
</el-icon>
<span>Navigator Two</span>
</el-menu-item>
<el-menu-item index="3" disabled>
<el-icon>
<document/>
</el-icon>
<span>Navigator Three</span>
</el-menu-item>
<el-menu-item index="4">
<el-icon>
<setting/>
</el-icon>
<span>Navigator Four</span>
</el-menu-item>
</el-menu>
</el-aside>
<el-container>
<el-header>
<el-row align="middle" style="height: 100%">
<el-col :span="1">
<el-icon v-show="isCollapse" @click="isCollapse=false"><Expand /></el-icon>
<el-icon v-show="!isCollapse" @click="isCollapse=true"><Fold /></el-icon>
</el-col>
</el-row>
</el-header>
<el-main>Main</el-main>
</el-container>
</el-container>
</div>
</template>
<style scoped lang="scss">
.el-container {
.el-aside {
background-color: slategrey;
height: 100vh;
width: 200px;
.el-menu{
height: 100%;
width: 100%;
}
}
.el-header {
background-color: #409EFF;
}
.el-main {
background-color: #E6A23C;
}
}
</style>