1.安装pinia和持久化插件
c
npm install pinia
c
npm install pinia-plugin-persistedstate
2.main.ts 文件中配置该插件
c
import { createSSRApp } from "vue";
import App from "./App.vue";
import { createPinia } from 'pinia';
import piniaPersistedState from 'pinia-plugin-persistedstate';
import TopNavigation from "./compontens/topNavigation.vue";
export function createApp() {
const pinia = createPinia();
// 配置持久化插件
pinia.use(piniaPersistedState);
const app = createSSRApp(App);
app.component('top-nav', TopNavigation)
app.use(pinia)
return {
app,
};
}
3.新建文件src/store/logintoken.ts
c
import { defineStore } from 'pinia';
import { ref } from "vue";
export const useLogintokenStore = defineStore('logintoken', () => {
// 会员信息
const profile = ref()
//定义一个函数来保存信息,本地缓存
const setProfile = (val: any) => {
profile.value = val
}
//定义一个函数来修改清理会员信息,清除全部存储
const clearProfile = () => profile.value = undefined
// 定义一个函数来修改或新增 profile 里面的值
const setProfileValue=(key: string, value: any)=> {
// 直接通过键名设置或更新值,如果键名不存在则新增
profile.value[key] = value;
}
// 定义一个函数来修改 profile 里面的值
const updateProfileValue = (key: string, value: any) => {
if (key in profile.value) {
// 如果键名存在于 profile 中,则更新其值
profile.value[key] = value;
console.log(profile)
} else {
console.warn(`Key "${key}" does not exist in profile.`);
}
}
// 定义一个函数来删除 profile 里面的值
const deleteProfileValue = (key: string) => {
if (key in profile.value) {
// 如果键名存在于 profile 中,则删除该属性
delete profile.value[key];
console.log(profile)
} else {
console.warn(`Key "${key}" does not exist in profile.`);
}
}
//记得 return
return { profile, setProfile, clearProfile, updateProfileValue, deleteProfileValue,setProfileValue }
},
{
persist: {
storage: {
getItem(key) {
return uni.getStorageSync(key)
},
setItem(key, value) {
uni.setStorageSync(key, value)
},
}
}
});
4.使用
存
c
import { useLogintokenStore } from '@/stores/logintoken'
let msg = {
idserveUserId: res.result.userId,
isFollowedWeChat: res.result.isFollowedWeChat,
openId: res.result.openId,
}
const memberStore=useLogintokenStore()
memberStore.setProfile(msg)
清除
c
const memberStore=useLogintokenStore()
memberStore.clearProfile()