1、引入下载Pinia
npm install pinia
2、下载持久化插件
npm install pinia-plugin-persist
3、main.js或main.ts引入
//引入pinia
import { createPinia } from "pinia";
//引入持久化插件
import persist from "pinia-plugin-persistedstate";
// 实例化 Pinia 并使用持久化插件
const pinia = createPinia().use(persist );
const app = createApp(App);
app.use(pinia);
4、vue3使用时创建Store目录index.ts
import { defineStore } from "pinia";
export const Store = defineStore("Store", {
// 其他配置...
state: () => {
return {
//控制左边导航栏 展开收起
isCollapse: false,
//存储用户id
userId: 0,
//存储账户名称
nickName: "",
//存储动态菜单的数据
menuList: [] as any,
};
},
//获取仓库值
getters: {
getisCollapse: (state) => state.isCollapse,
getUserId: (state) => state.userId,
getNickName: (state) => state.nickName,
getMenuList: (state) => state.menuList,
},
//改变state的值
actions: {
setisCollapse(isCollapse: boolean) {
this.isCollapse = isCollapse;
},
setUserId(userId: any) {
this.userId = userId;
},
setNickName(nickName: any) {
this.nickName = nickName;
},
setMenuList(menuList: any) {
this.menuList = menuList;
},
},
persist: {
//持久户化操作
storage: localStorage,
paths: ["userId", "nickName", "menuList"],
},
});
4、uni-app使用在持久化属性上有些不同
import {defineStore} from "pinia";
export const Store = defineStore("Store", {
// 其他配置...
state: () => {
return {
//用户Id
userId: '',
//用户账户
userName: '',
//用户昵称
nickName: '',
//用户手机号
phone: '',
//单个商品数据
goodItem:[]
};
},
//获取仓库值
getters: {
getUserId: (state) => state.userId,
getUserName: (state) => state.userName,
getNickName: (state) => state.nickName,
getPhone: (state) => state.phone,
getGoodItem: (state) => state.goodItem,
},
//改变state的值
actions: {
setUserId(userId) {
this.userId = userId;
uni.setStorage({ key: 'userId', data: userId });
},
setUserName(userName) {
this.userName = userName;
uni.setStorage({ key: 'userName', data: userName });
},
setNickName(nickName) {
this.nickName = nickName;
uni.setStorage({ key: 'nickName', data: nickName });
},
setPhone(phone) {
this.phone = phone;
uni.setStorage({ key: 'phone', data: phone });
},
setGoodItem(item) {
this.goodItem = item;
uni.setStorage({ key: 'goodItem', data: item });
},
},
});
5、具体使用
<script setup lang="ts">
//引入文件
import { Store } from '../../../../store';
//拿到store
const store = Store()
//这里就实现全组件调用 get set方法
stote.get
store.set
</script>