之前用 pinia 做左边导航栏菜单,一开始是用localStorage保存数据的,后来想应该有插件做这种数据持久化。所以便找到了localStorage。
1.安装插件
yarn add pinia-plugin-persistedstate
2.引入插件
import { createPinia } from 'pinia';
//引入持久化插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
//添加持久化支持
pinia.use(piniaPluginPersistedstate);
export default pinia
3.store中使用
import {defineStore} from 'pinia';
/**
*
* @methods 设置菜单信息
*/
export const useMenuStore = defineStore('menu',{
persist: true,//数据持久化设置
state: (): MenuInfoState => ({
collapse: true,
menu: {
id: '',
name: '',
title: '',
path: '/',
children: [],
type: 0
},
}),
getters:{
menus(state){
return state.menu.children;
},
},
actions: {
async gen(datas:MenuJsonInfo[]) {
const that = this;
const map = {};
datas.forEach((item: MenuJsonInfo) =>{
map[item.id] = {...item, children: [] };
});
const findParent = (parentId: number, item: MenuJsonInfo)=>{
if(parentId == 0 ){
that.menu.children?.push(map[item.id]);
}else {
const parent = map[parentId.toString()];
if(parent){
parent.children.push(item);
}
}
};
datas.forEach((item: MenuJsonInfo) =>{
findParent(item.parentId, map[item.id]);
});
},
handleCollape(){
this.collapse = !this.collapse;
return this.collapse;
},
clear(){
this.menu.children =[];
},
},
});