把手搭建vue前后端管理系统-TAB标签通过pinia来进行管理(二十六)
目标:通过pinia的store来进行组件状态的统一管理,这样大家都可以共用到这个组件的状态信息,就可以实现组件的联动
一、添加侧边栏菜单的点击事件:
1、CommonAside.vue里面添加click的事件
<el-menu-item
v-for="item in noChildren"
:index ="item.path"
:key="item.path"
@click="handelMenu(item)"
>
<el-menu-item-group >
<el-menu-item
v-for="(subItem,subIndex) in item.children"
:index ="subItem.path"
:key="subItem.path"
@click="handleMenu(subItem)"
>
2、写入handleMenu的方法:
const router=useRouter() const route=useRoute() const handleMenu=(item)=>{ router.push(item.path) }
二、stores下面的index.js里面增加tags的状态:
function initState(){
return {
isCollapse:false,
tags:[
{
path:'/home',
name:'home',
label:'首页',
icon:'home'
}
],
}
}
三、CommonTab.vue里面进行tags的动态获取,tags的值就是从store的state里面进行获取,而不是静态的在这个里面写一个ref的数组了:
import {useAllDataStore} from "../stores/index.js";
const store=useAllDataStore()
const tags=computed(()=>store.state.tags)
四、在stores里面新增selectMenu的动作并暴漏出去
export const useAllDataStore = defineStore('allData', (a) => {
//在 Setup Store 中:
//ref() 就是 state 属性
//computed() 就是 getters
//function() 就是 actions
const state = ref(initState())
//需要把所有定义的state,getters,actions返回出去
// 如果传进来的item的数组的值=home就不做操作,如果不等于home就查找state中tags数组的下标
//findIndex(item=>item.name=val.neme)就相当于findIndex(item){item.name=val.name),,就是赋值了
// 参数:回调函数,而回调函数中的参数代表数组中的元素参数
// 返回值 : 返回值是元素在数组中的位置,差找不到则显示-1,没有找到,就将val的值插入到tags的数组里面,这样标签就可以增加了
function selectMenu(val) {
if (val.name === "home") {
state.value.currentMenu = null;
} else {
let index = state.value.tags.findIndex(item => item.name === val.name)
index === -1 ? state.value.tags.push(val) : "";
}
}
return {
state,
selectMenu,
};
})
五、在CommonAside.vue里面的handleMenu里进行使用
const handleMenu=(item)=>{
router.push(item.path);
store.selectMenu(item)
}
六、最终的效果: