安装插件
npm install pinia pinia-plugin-persist
pinia进行注册
创建index.ts
import { createPinia } from 'pinia';
//对外暴露大仓库
export default createPinia();
在mian.ts
//引入pinpa
import { createApp } from 'vue'
//引入根组件
import App from './App.vue'
const app = createApp(App)
import Pinia from './store/index'
//注册Pinpa持久化插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
Pinia.use(piniaPluginPersistedstate)
app.use(Pinia)
app.mount('#app')
调用
import {defineStore} from 'pinia'
import {reqCode,reqUserLogin} from '../../api/hospital/index'
import {PhoneTy} from '../../api/hospital/type'
const useUserStore = defineStore('User',{state:()=>{return{visiable: false,//用于控制登录组件的dialog显示与隐藏code: '',//存储用户的验证码,//存储用户的信息userInfo:JSON.parse(localStorage.getItem('USERINFO') as string) || {}}},actions:{//获取短信验证async getCode(value:string){const r:PhoneTy = await reqCode(value) as anyif(r.code == 200){this.code = r.data// console.log(this.code,'this.code1')}console.log(this.code,'this.code2')},//登陆用户async reqUserLogin(value:object){const r = await reqUserLogin(value)this.userInfo = r.data// localStorage.setItem('USERINFO',JSON.stringify(this.userInfo))console.log(r)}},// 在这里进行自定义配置persist: {key:'USERINFO', // 存储的key, 默认store.$id// storage: sessionStorage, // 存储的类型,默认localStoragepaths:['userInfo']// 指定 state 中哪些数据需要被持久化, 默认undefined}})
export default useUserStore
即使是对象数组,也可以直接放进去,不需要JSON转换
取值的话需要转换
userInfo:JSON.parse(localStorage.getItem('USERINFO') as string) || {}
使用的话正常和存储在本地一样调用就行