vu3+element-plus 实现左侧菜单栏
API 接口返回的数据格式
{
"success": true,
"code": 2000,
"msg": "成功",
"data": [
{
"id": 3,
"parent_id": "0",
"menu_name": "系统首页",
"icons": "el-icon-s-home",
"url": "/",
"front_url": "",
"method": "",
"created_at": "2022-06-29 10:33:04",
"children": [
{
"id": 4,
"parent_id": "3",
"menu_name": "数据看板",
"icons": "el-icon-s-home",
"url": "/v1/api/dashboard/index",
"front_url": "board",
"method": "POST",
"created_at": "2022-06-29 10:48:39",
"children": null
}
]
},
{
"id": 5,
"parent_id": "0",
"menu_name": "账号管理",
"icons": "el-icon-s-custom",
"url": "/",
"front_url": "",
"method": "",
"created_at": "2022-06-29 10:50:23",
"children": [
{
"id": 6,
"parent_id": "5",
"menu_name": "管理员列表",
"icons": "el-icon-s-custom",
"url": "/v1/api/accounts/get/account/list",
"front_url": "accountList",
"method": "POST",
"created_at": "2022-06-29 10:51:13",
"children": null
},
{
"id": 15,
"parent_id": "5",
"menu_name": "角色列表",
"icons": "el-icon-s-custom",
"url": "/v1/api/role/get/role/list",
"front_url": "roleList",
"method": "POST",
"created_at": "2022-06-29 10:57:59",
"children": null
}
]
},
{
"id": 7,
"parent_id": "0",
"menu_name": "菜单管理",
"icons": "el-icon-menu",
"url": "/",
"front_url": "",
"method": "",
"created_at": "2022-06-29 10:51:35",
"children": [
{
"id": 8,
"parent_id": "7",
"menu_name": "菜单列表",
"icons": "el-icon-menu",
"url": "/v1/api/menu/get/menu/list",
"front_url": "menusList",
"method": "POST",
"created_at": "2022-06-29 10:52:10",
"children": null
}
]
}
]
}
在store里面创建菜单数组
export default createStore({
state: {
/** 左侧菜单列表 */
menuListAll: [],
},
mutations: {
// 菜单列表
async menuList(state) {
try {
let res = await menu(); // api接口 数据格式 如上贴出来的
if (res) {
state.menuListAll = res.data
}
} catch (err) {
}
},
},
actions: {
/** 请求左侧菜单 */
loadmenuList(obj) {
window.localStorage.getItem('token') && obj.commit('menuList')
}
},
modules: {
},
plugins: [
createPersistedstate({
storage: window.sessionStorage,
key: "store",
reducer(state) {
return {
menuListAll: state.menuListAll,
}
}
})
]
})
首页 从store里面取出菜单列表数据,取之前先判断下是否登陆
import { useRouter } from "vue-router";
import store from "@/store/index.ts"
<template>
<el-sub-menu :index="item.parent_id" v-for="item in store.state.menuListAll" :key="item.parent_id">
<template #title>
<i class="el-icon-s-home"></i>
<span class="caidan-auth">{{ item.menu_name }}</span>
</template>
<el-menu-item :index="item2.front_url" v-for="item2 in item.children" :key="item2.id" @click="goUrl(item.menu_name,item2.menu_name,item2.front_url)">
<i class="item.icons"></i>
<span class="caidan-auth">{{ item2.menu_name }}</span>
</el-menu-item>
</el-sub-menu>
</template>
<script setup>
const router = useRouter()//路由跳转
const initMenusList = async () =>{//判断是否已经存在token是否已经登录
if(!window.localStorage.getItem("token")){
router.push("/login")
}else{
//console.log(store.state.menuListAll);
store.state.menuListAll.length || store.dispatch("loadmenuList");
}
}
initMenusList()
</script>
效果: