把手搭建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) 
}

六、最终的效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

miumiubear

你的鼓励将是我前进最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值