下文代碼基于
- vue 3.x
- pinia 2.x
定義
pinia/index.ts
import { useUserStore } from './user';
// 統(tǒng)一導出useStore方法
export const useStore = () => {
return {
user: useUserStore(),
};
};
pinia/user.ts
import { defineStore } from 'pinia';
interface UserStore {
name: string;
}
export const useUserStore = defineStore('user', {
state: (): UserStore => ({
name: '',
}),
getters: {
myName: (state) => {
return state.name;
}
},
actions: {
setName(name: string) {
this.name = name;
},
clearName() {
this.setName('');
},
},
// 開啟數據持久化
// 1.所有數據持久化
// persist: true,
// 2.持久化存儲插件自定義配置
persist: {
// 修改存儲中使用的鍵名稱姚建,默認為當前 Store的 id
key: 'USER_KEY',
// 修改為 sessionStorage吱殉,默認為 localStorage
storage: window.sessionStorage,
// 部分持久化狀態(tài)的點符號路徑數組,[]意味著沒有狀態(tài)被持久化(默認為 undefined 稿湿,持久化整個狀態(tài))
paths: ['name'],
},
});
index.ts
import { createApp } from 'vue';
import { createPinia } from 'pinia';
// pinia 數據持久化插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
import App from './App.vue';
/**
* pinia
*/
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
createApp(App).use(pinia).mount('#app');
使用
xxx/xx.vue(vue setup)
import { useStore } from '@/pinia';
const { user } = useStore();
console.log(user.name);
user.clearName();
// ...
注意:
useStore()
在非setup
環(huán)境下饺藤,需要包含在方法中調用