vue3 + pinia 持久化缓存

pinia

文档 pinia
下载

yarn add pinia

main.ts

import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';

createApp(App).use(createPinia()).mount('#app');

src/store/rank.ts

import { getRank } from '@/api/rank';
import { defineStore } from 'pinia';
import { useAuthStore } from './auth-store'

type State = {
  age: number;
};
const id = '@@rank' as const;

export const useRankStore = defineStore(id, {
  // other options...
  state: (): State => ({ age: 18 }),
  getters: {
	double: (state) => state.age* 2,
  },
  actions: {
    async getRank() {
      // 访问其他 store 
      const auth = useAuthStore()
      auth.getUserInfo()
      
      return await getRank();
    },
  },
});

.vue

  import { useRankStore } from '@/store/rank';
  import { storeToRefs } from 'pinia'; // 保持其响应式
 
  const rankStore = useRankStore();
  const { age } = storeToRefs(rankStore);
  rankStore.getRank()

持久化 pinia

文档 pinia-plugin-persist
下载

yarn add pinia-plugin-persist

tsconfig.json
将 pinia-plugin-persist 类型定义文件添加到 tsconfig 文件。

{
  "compilerOptions": {
    "types": [
      "pinia-plugin-persist"
    ]
  },
}

main.ts 改造

import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';
import piniaPersist from 'pinia-plugin-persist';

const pinia = createPinia();
pinia.use(piniaPersist);

createApp(App).use(pinia).mount('#app');

src/store/rank.ts

import { getRank } from '@/api/rank';
import { defineStore } from 'pinia';

type State = {
  age: number;
};
const id = '@@rank' as const;
const initialState: State = {
  age: 18,
};

export const useRankStore = defineStore(id, {
  state: () => ({...initialState}),
  getters: {},
  actions: {
    async getRank() {
      return await getRank();
    },
  },
  persist: {
  	// 默认情况下,整个状态将存储在 sessionStorage 中。
    enabled: true,
    
    strategies: [
      { 
      	// 默认情况下,存储的 key 为 store 的 id(@@rank), 更改 key 
      	key: 'newRant',
      	// 默认情况下,整个状态将存储在 sessionStorage 中。更改存储 localStorage 
     	storage: localStorage, 
     	// 默认情况下,整个状态是持久的,但您可以通过在每个策略中设置 paths 键来指定要保留的状态键
      	paths: ['age'] 
      },
    ],
  },
});

[Vue warn]: injection “Symbol(pinia)“ not found.

你可能感兴趣的:(vue,vue.js)