Vue3菜单展开和收起实现
作者:jnfy
在Vue项目中实现首页布局,包括可收放的左侧菜单和主体内容区,在store中管理菜单状态,通过修改isCollapse状态控制菜单的展开与收起,在home.vue中编写左侧菜单栏的代码和样式,实现一个响应式的用户界面
Vue3菜单展开和收起
先确定我们首页的布局
我们使用一下这种,在src/views/home.vue:
<template> <div class="common-layout"> <el-container> <el-aside width="200px">Aside</el-aside> <el-container> <el-header>Header</el-header> <el-main>Main</el-main> </el-container> </el-container> </div> </template>
先写一下我们左边的菜单
菜单可以收起和展开,所以我们在store/module/common.js 中定义一个 isCollapse
状态和修改isCollapse
的方法。
import { defineStore } from 'pinia' export const useCommonStore = defineStore('common', { state: () => { return { token: null, isCollapse: false, //默认值 } }, actions: { //改变isCollapse updateCollapse() { this.isCollapse = !this.isCollapse }, }, persist: true, })
这是我要实现的左侧菜单栏代码和样式
//src/views/home.vue <template> <div> <el-container> <el-aside @mouseover="mouseover" :width="store.isCollapse ? '100px' : '258px'"> <div class="sidebar"> <div class="ga-flex ga-ai-c ga-j-sb logo-warp p-15"> <img class="logo m-r-10" src="./../assets/images/galaxy-logo.png" /> <h2 v-if="!store.isCollapse" class="flex-1">GaUI</h2> <a @click="open" v-if="!store.isCollapse"> <i class="icon-align-left f-20"></i> </a> </div> <div class="p-15"> <el-menu active-text-color="#534686" class="el-menu-vertical-demo" :collapse="store.isCollapse" @open="handleOpen" @close="handleClose" > <el-sub-menu index="1"> <template #title> <el-icon><location /></el-icon> <span>Navigator One</span> </template> <el-menu-item index="1-1">item one</el-menu-item> <el-menu-item index="1-2">item two</el-menu-item> </el-sub-menu> </el-menu> </div> </div> </el-aside> <el-container> <el-header> <div>header</div> </el-header> <el-main> Main </el-main> <el-footer>Footer</el-footer> </el-container> </el-container> </div> </template>
<script setup> import { useCommonStore } from '../store/module/common.js' const store = useCommonStore() // 点击展开收起 const open = () => { store.updateCollapse() } // 如果是收起状态,那么鼠标移入时则展开 const mouseover = () => { if (store.isCollapse) { store.updateCollapse() } } const handleOpen = (key, keyPath) => { //console.log(key, keyPath) } const handleClose = (key, keyPath) => { //console.log(key, keyPath) } </script>
<style lang="scss" scoped> .sidebar { background-color: #ffffff; transition: 0.3s; min-height: 100vh; .logo-warp { padding: 20px 25px; box-shadow: -9px 0 20px rgb(89 102 122 / 10%); .logo { width: 50px; height: 50px; } a{ &:hover{ color: #534686; } } } .el-sub-menu__title:hover { background-color: var(--el-menu-hover-bg-color); } } .el-aside { box-shadow: 0 0 21px 0 rgb(89 102 122 / 10%); } .el-menu { border-right: none !important; } .el-menu-vertical-demo:not(.el-menu--collapse) { width: 228px; min-height: 100%; } </style>
左侧菜单效果:
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。