- 安装依赖
pnpm i pinia pinia-plugin-persistedstate @nuxt/devalue -S
- 创建store文件夹,创建持久化插件/store/plugins.ts
import { App } from 'vue'
import { createPinia } from 'pinia'
import devalue from '@nuxt/devalue'
import { createPersistedState } from 'pinia-plugin-persistedstate'
export const pinia = createPinia()
export const painaInstall = (app: App) => {
pinia.use(
createPersistedState({
storage: {
getItem(key: string): string | null {
return uni.getStorageSync(key)
},
setItem(key: string, value: string) {
uni.setStorageSync(key, value)
},
},
}),
)
app.use(pinia)
devalue(pinia.state.value)
}
- mian.ts中使用插件
import { createSSRApp } from 'vue'
import App from './App.vue'
import { painaInstall } from '@/store/plugins'
export function createApp() {
const app = createSSRApp(App)
app.use(painaInstall)
return {
app,
}
}
- 创建 /store/index.ts
import { defineStore, acceptHMRUpdate } from 'pinia'
export const useStore = defineStore('main', {
persist: {
key: 'pinia-main',
paths: ['codeTimoutNum', 'codeTimeoutDate'],
},
state: () => {
return {
userInfo: {} as ObjectType,
token: '',
codeTimoutNum: 0,
codeTimeoutDate: 0,
}
},
actions: {
async logout(): Promise<any> {
return ''
},
},
})
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useStore, import.meta.hot))
}
|