1、下载安装pinia,引入pinia
javascript
//stores->index.ts
import { createPinia } from 'pinia'
import persist from 'pinia-plugin-persistedstate' //持久化插件
// 创建 pinia 实例
const pinia = createPinia()
// 使用持久化存储插件
pinia.use(persist)
// 默认导出,给 main.ts 使用
export default pinia
// 模块统一导出
export * from './modules/member'
// export * from './modules/xxxxx' //如果有多个模块,依次导出即可
// export * from './modules/xxxxx' //如果有多个模块,依次导出即可
并且在main.ts中引入:
javascript
import { createSSRApp } from 'vue'
import pinia from './stores'
import App from './App.vue'
export function createApp() {
const app = createSSRApp(App)
app.use(pinia)
return {
app,
}
}
2、定义pinia,并持久化
javascript
//stores->modules->member.ts
import { defineStore } from 'pinia'
// 定义 Store
export const useMemberStore = defineStore('member', {
state: () => ({
profile: null,
}),
actions: {
setProfile(obj: any) {
this.profile = obj
},
clearProfile() {
this.profile = null
},
},
//pinia数据持久化
persist: {
storage: {
getItem(key) {
return uni.getStorageSync(key)
},
setItem(key, value) {
return uni.setStorageSync(key, value)
},
},
},
})