本文主要是介绍20240618每日前端---------vue3集成pinia,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
pinia
Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。
集成
安装pinia依赖
yarn add pinia
npm install pinia
pnpm i pinia
安装pinia持久化缓存pinia-plugin-persistedstate
npm i pinia-plugin-persistedstate
yarn add pinia-plugin-persistedstate
pnpm i pinia-plugin-persistedstate
使用
在main.ts引入
import {createApp} from 'vue';
import App from './App.vue';
import pinia from "@/stores";const app = createApp(App);
app.use(pinia).mount("#app");
定义stores
index.ts
import {createPinia} from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);export default pinia;
modules/user.ts
import { defineStore } from "pinia";
import { UserState } from "@/stores/interface";
import piniaPersistConfig from "@/stores/helper/persist.ts";export const useUserStore = defineStore({id: "dive-yang",state: (): UserState => ({token: "",userInfo: {userName:"",userId:"",userCode:"",userAvatar:"",userEmail:"",userPhone:"",userRole:"",userStatus:"",userCreateTime:"",}}),getters: {},actions: {// Set TokensetToken(token: string) {this.token = token;},// Set setUserInfosetUserInfo(userInfo: UserState["userInfo"]) {this.userInfo = userInfo;}},persist: piniaPersistConfig("dive-yang")
});
interface/index.ts
export interface UserState{token:string,userInfo:{userName:string,userId:string,userCode:string,userAvatar:string,userEmail:string,userPhone:string,userRole:string,userStatus:string,userCreateTime:string,}
}
hepler/persist.ts
import { PersistedStateOptions } from "pinia-plugin-persistedstate";/*** @description pinia 持久化参数配置* @param {String} key 存储到持久化的 name* @param {Array} paths 需要持久化的 state name* @return persist* */
const piniaPersistConfig = (key: string, paths?: string[]) => {const persist: PersistedStateOptions = {key,storage: localStorage,// storage: sessionStorage,paths};return persist;
};export default piniaPersistConfig;
vue3使用
index.vue
import {useUserStore} from "@/stores/modules/user";let token = ref('user' + Math.floor(Math.random() * 1000) + 1);const userStore = useUserStore();let userInfo = userStore.userInfo;userInfo.userCode = token.value;userStore.setUserInfo(userInfo);
至此,vue3实战集成pinia已完成。
这篇关于20240618每日前端---------vue3集成pinia的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!