uni-app和vue3关于Pinia使用与持久化

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值