vue2以前一直使用vuex实现状态管理
vue3之后推出了pinia…
直观、类型安全、轻便灵活的Vue Store,使用具有DevTools支持的组合api
由于pinia本身没有提供设置缓存的功能,不过可以结合pinia-plugin-persistedstate
实现
npm i pinia -S
npm i pinia-plugin-persistedstate -S
import { createApp } from "vue";
import { createPinia } from "pinia";
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import App from "./App/index.vue";
const app = createApp(App);
// 注册 pinia , 并在 pinia 使用 piniaPluginPersistedstate
app.use(createPinia().use(piniaPluginPersistedstate));
app.mount("#app");
大部分开发都默认在 stores 目录放置缓存相关文件
pinia有两种写法,其中一个是同vuex类似的选项式(这种才能结合pinia-plugin-persistedstate
设置浏览器缓存),还有一个就是更符合vue3组合式写法
import { defineStore } from "pinia";
export interface MapState {
address: string;
}
const { SIS_STORE_NAME } = import.meta.env;
export const useMapStore = defineStore(SIS_STORE_NAME + "map", {
state: (): MapState => ({
address: "",
}),
getters: {},
actions: {
setAdress(address: string) {
this.address = address;
},
clearMessage() {
this.address = "";
},
},
persist: {
/**
* 使用的存储
* @default $store.id
*/
key: SIS_STORE_NAME + "map",
/**
* 存储位置
* @default localStorage
*/
storage: sessionStorage,
/**
* 需要设置缓存的state 如果未设置即存储所有state
* @default undefined
*/
// paths: [],
/**
* 存储之前
* @default null
*/
beforeRestore: () => {},
/**
* 存储之后
* @default undefined
*/
afterRestore: () => {},
/**
* 启用时在控制台中记录错误。
* @default false
*/
debug: true,
},
});
import { ref, computed } from "vue";
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", () => {
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++;
}
return { count, doubleCount, increment };
});
如果是字段数据,需要使用storeToRefs
获取为响应式的,方法不用
虽然上述两种定义不同,但调用使用方式是一样的
import { storeToRefs } from "pinia";
import { useMapStore } from "./stores/mapState";
import { useCounterStore } from "./stores/counter";
const { address } = storeToRefs(useMapStore())
const { setAdress, clearMessage } = useMapStore()
setAdress('')
clearMessage()
const { count } = storeToRefs(useCounterStore())
const { increment } = useCounterStore()
increment()
console.log(count)
import type { App } from "vue";
import { createPinia } from "pinia";
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const store = createPinia().use(piniaPluginPersistedstate);
// 全局注册 store
export function setupStore(app: App<Element>) {
app.use(store);
}
export { store };
import { createApp } from "vue";
import App from "./App/index.vue";
import { setupStore } from "./stores";
const app = createApp(App);
// 全局注册 状态管理(store)
setupStore(app)
app.mount("#app");
如有启发,可点赞收藏哟~