一、插件版本:
"pinia": "^2.0.23",
"pinia-plugin-persist": "^1.0.0",
"vue": "^3.4.27"
二、store目录
src/store/index.ts
import type { App } from 'vue'; import { createPinia } from 'pinia'; import piniaPersist from 'pinia-plugin-persist'; const store = createPinia(); store.use(piniaPersist); export function setupStore(app: App<Element>) { app.use(store); } export { store };src/store/tableStore.ts
import { Ref, ref } from 'vue'; import { defineStore } from 'pinia'; import { store } from '@/store'; export interface ITableStoreState { tableRef: Ref; list: Map<any, any>[]; } export const tableOrgStore = defineStore({ id: 'tableOrganization', state: (): ITableStoreState => ({ tableRef: ref(), list: [], }), persist: { enabled: true, }, getters: { getList(): ITableStoreState['list'] { return this.list; }, }, actions: { setList(info: ITableStoreState['list']) { this.list = info; }, }, }); // Need to be used outside the setup export function useTableStoreWidthOut() { return tableOrgStore(store); }三、main.ts
。。。省略。。。 // 挂载状态管理 setupStore(app); 。。。省略。。。四、在main.ts所在项目的任意组件中使用:
import { storeToRefs } from 'pinia'; import { useTableStoreWidthOut } from '@/store/modules/tableStore'; const tableStore = useTableStoreWidthOut(); const { tableRef, getList } = storeToRefs(tableStore); // 响应式数据使用storeToRefs包裹再解构获取 const { setList } = tableStore; // function方法直接解构获取使用tableRef示例:
<template> <button @click="handleClick">click</button> <my-list ref="tableRef" /> </template> <script lang="ts" setup> import { storeToRefs } from 'pinia'; import { useTableStoreWidthOut } from '@/store/modules/tableStore'; import MyList from './MyList.vue'; const tableStore = useTableStoreWidthOut(); const { tableRef } = storeToRefs(tableStore); // 响应式数据使用storeToRefs包裹再解构获取 const handleClick = () => { console.log('===tableRef====', tableRef); }; </script>五、参考资料
https://pinia.vuejs.org/core-concepts/
https://prazdevs.github.io/pinia-plugin-persistedstate/zh/guide/
https://cn.vuejs.org/api/application.html