安装pinia
npm install pinia --save
创建 menu.ts 和index.ts
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5a48bb8382803639fa9609dcd056fa11.png)
menu.ts内容
import { defineStore } from 'pinia'
import { ref } from 'vue';
export const useMeanStore = defineStore('mean', () => {
const menuList = ref([])
const permList = ref([])
const hasRoute = ref(false)
function changeRouteStatus(state: any) {
hasRoute.value = state
sessionStorage.setItem("hasRoute", state)
}
function setMenuList(menus: any) {
menuList.value = menus
}
function setPermList(authoritys: any) {
permList.value = authoritys
}
return {
changeRouteStatus,
setMenuList,
setPermList
}
})
index.ts 内容
import { defineStore } from 'pinia'
import { type RouteRecordRaw } from 'vue-router'
import { ref } from 'vue';
let modules = import.meta.glob("../views/*/*.vue")
export const useStore = defineStore('myStore', {
state: () => {
return {
routes: [] as Array<RouteRecordRaw>
}
},
getters: {},
actions: {
addRoutes(data: Array<any>, router: any) {
data.forEach(m => {
this.routes.push({
path: m.path,
name: m.name,
component: modules[`../views/${m.component}`],
})
})
this.routes.forEach(m => router.addRoute("home",m))
console.log(router);
},
},
})
export const useMeanStore = defineStore('mean', () => {
const menuList = ref([])
const permList = ref([])
const hasRoute = ref(false)
function changeRouteStatus(state: any) {
hasRoute.value = state
sessionStorage.setItem("hasRoute", state)
}
function setMenuList(menus: any) {
menuList.value = menus
}
function setPermList(authoritys: any) {
permList.value = authoritys
}
return {
menuList,
permList,
hasRoute,
changeRouteStatus,
setMenuList,
setPermList
}
})
在路由守卫中请求路由数据
import router from "@/router/index"
import { useStore,useMeanStore } from "../stores";
import { routerApi } from '../server'
router.beforeEach((to, from, next) => {
const useMean = useMeanStore()
if (to.path !== '/home' && to.path !== '/') {
const store = useStore()
if (store.routes.length < 1) {
routerApi().then(res => {
useMean.setMenuList(res.data.data)
useMean.setPermList(res.data.data)
store.addRoutes(res.data.data, router)
next({ path: to.path, replace: true })
}).catch(_ => {
next()
})
} else {
next()
}
} else {
next()
}
})
router.afterEach(() => {
})
使用
import { useStore, useMeanStore } from "../stores";
import { storeToRefs } from "pinia";
const useMean = useMeanStore()
const { menuList, permList, hasRoute } = storeToRefs(useMean);
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/77c5f27a75ad830f293c3b1f26722537.png)