uniapp vue3版本中使用pinia 以及持久化处理
使用hbuiderx创建的项目 里面已经包含了
一.这里简单的说一下 引入方式 有的小伙伴可能没分清
在main.js中直接引入
我这里实现 帮这些引入抽离抽来,在根目录抽离一个出来在根目录新建一个global
文件下 下面建立global.js
文件
新建global/global.js
import { createPinia } from 'pinia'
import persist from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(persist)
export default function globalUnit(app) {app.use(pinia)
}
main.js
中引用
import { createSSRApp } from 'vue'
import App from './App.vue'
import globalUnit from '@/global/global.js'// #ifdef VUE3
export function createApp() {const app = createSSRApp(App)globalUnit(app)return {app,}
}
// #endif
注意这里有的写发是as 别名的方式
import * as Pinia from 'pinia'app.use(Pinia.createPinia());
其实也是 帮pinia
中的所用东西 拿出来 用个别名Pinia
来接收使用
const pinia = createPinia() 也就是 Pinia.createPinia()
createPinia 也就是 pinia
中的一个方法而已
二:废话不多说直接开始使用
举例都是在根目录新建 个人习惯 ,根据自己的方式只要路径对就行
新建stores/userStore.js
userStore.js
如下
就比如登录的时候存储的用户信息 userInfo
import { defineStore } from 'pinia';export const useUserStore = defineStore('user', {state: () => ({userInfo: {},}),actions: {login(userInfo) {this.userInfo = userInfo;}},// 可选:持久化插件(如使用 localStorage)persist: true,
});
- 在页面中使用 引入
比如在h5login.vue
中
<template><view><view class="logonbox"><uni-easyinput maxlength="11" v-model="phone" placeholder="请输入手机号"></uni-easyinput><uni-easyinput v-model="password" type="password" placeholder="请输入密码"></uni-easyinput><button type="primary" @click="handLogin">登录</button></view></view>
</template><script setup>import { useUserStore } from '@/stores/userStore'const userStore = useUserStore()let phone = ref("123456")let password = ref("6666")const handLogin = () => {// 这里自己接口去获取数据 最后传进去晚上 这里模拟一个objlet obj ={name:"老六",token:"asdaklqjkwewqeq12312daksds"}userStore.login(obj )}
</script><style scoped lang="less">.logonbox {width: 610rpx;height: 300rpx;background: #f4f4f4f4;margin: 200rpx auto;display: flex;flex-direction: column;justify-content: center;}
</style>
三:如果你没开启 持久存储的时候你强行刷新页面 值是会丢失的
开启之后再本地储存里面就是多一个