關于pinia的使用和持久化方式(pinia-plugin-persistedstate)
更新時間:2025年02月17日 14:28:28 作者:堅定信念,勇往無前
本文介紹了Pinia的使用方法,包括安裝和配置插件pinia-plugin-persistedstate,以及在項目中創(chuàng)建和使用Store模塊,同時,還講解了Pinia的state、getters和actions的使用,并提供了在uniapp中使用持久化插件的總結
pinia的使用和持久化(pinia-plugin-persistedstate)
安裝插件
- npm install pinia
- npm install pinia-plugin-persistedstate
文件配置
方法一
- 在store/index.js文件中進行初始化配置
import { createPinia } from 'pinia' import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' export function setupStore(app) { const pinia = createPinia() pinia.use(piniaPluginPersistedstate) //使用持久化存儲插件 app.use(pinia) } export * from './modules/user'
- 在main.js入口文件中引入pinia配置
import { createSSRApp } from "vue"; import App from "./App.vue"; /** pinia */ import { setupStore } from './store/index.js' export function createApp() { const app = createSSRApp(App); setupStore(app); //pinia return { app, }; }
方法二
- 直接在main.js文件中進行配置
import { createApp } from 'vue' import App from './App.vue' // pinia import { createPinia } from 'pinia' // pinia中數(shù)據(jù)持久化 import { persistedState } from 'pinia-plugin-persistedstate' // pinia配置 const pinia=createPinia() pinia.use(persistedState) createApp(App) .use(pinia) .mount('#app')
創(chuàng)建pinia模塊
- store/modules/user.js
頁面中使用
state
//user.js import { defineStore } from "pinia"; /** * 參數(shù)1:命名空間名稱 唯一id * 參數(shù)2: { state getters actions persist } */ // useUserStore: 推薦使用 use + id + Store 來命名 export const useUserStore = defineStore("User", { state: () => ({ userName: "", age:18, obj:{ money:9999,house:99 }, hobby:[ { id: 1, name: '籃球', level: 1 }, { id: 2, name: 'rap', level: 10 } ] }), getters: { // 類似于計算屬性,參數(shù)state指向defineStore下的state doubleAge(state) { return state.age * 2; }, //在getter中 使用另一個getter this指向當前存儲庫 addOneAge() { return this.doubleAge + 1; }, //返回一個函數(shù) returnFunction(state) { return function (id) { return state.hobby.find((item) => item.id == id); }; }, }, //可以通過this訪問整個store實例的所有操作,支持異步操作 actions: { //非異步操作 addAge(e) { console.log("接受的數(shù)據(jù)", e); //e是外部調用方法傳遞的參數(shù) //方法一 this.age = this.age + e; //方法二 // this.$patch((state) => { // state.age += e; // }); }, // 模擬異步 asynchronous() { return new Promise((resolve) => { setTimeout(() => { resolve("模擬異步返回值"); }, 2000); }); }, // 異步操作 async getList() { const res = await this.asynchronous(); console.log(res); }, }, persist:true, });
- State類似于組件中的data
- Store在它被使用之前是不會創(chuàng)建的,我們可以通過調用use函數(shù)來使用Store。
- 一旦 store 被實例化,你就可以直接在 store 上訪問 state、getters 和 actions 中定義的任何屬性
- store 是一個用reactive 包裹的對象,這意味著不需要在getter 之后寫.value,但是,就像setup 中的props 一樣,我們不能對其進行解構
<template> <div class="content"> <div>我叫{{ userName }},今年{{ age }}歲</div> <div>財富有{{ obj.money }}萬元</div> <div>其他資產有{{ obj.house || obj.friend }}個</div> <div>愛好有</div> <div v-for="item in hobby" :key="item.id"> <div>{{ item.name }}</div> </div> <button @click="editPiniaHandler">點擊修改</button> <button @click="editAll">點擊修改全部</button> <button @click="replaceAll">替換</button> <button @click="resetBtn">重置</button> </div> </template> <script setup> // import { ref } from 'vue'; import { useUserStore } from '@/store/index.js' //引入倉庫 import { storeToRefs } from "pinia"; //引入pinia轉換 const userInfoStore = useUserStore() // const { username, age, like, hobby } = userInfoStore //直接結構賦值 不是響應式 const { userName, age, hobby, obj } = storeToRefs(userInfoStore); // 響應式 // 一個一個修改 const editPiniaHandler = () => { userInfoStore.userName = "小明"; userInfoStore.age += 1; }; //使用$patch方法 以對象的形式一次性修改 const editAll = () => { userInfoStore.$patch({ userName: "鴨蛋", age: 21, }); }; // $state 替換 state 為新對象 const replaceAll = () => { userInfoStore.$state = { userName: '狗子', age: '22', obj: { money: 10, friend: 1 }, hobby: [ { id: 1, name: "足球", level: 1 }, { id: 2, name: "唱歌", level: 10 }, ], } } // 重置state const resetBtn = () => { userInfoStore.$reset() } </script> <style lang="scss" scoped> .content { display: flex; flex-direction: column; align-items: center; justify-content: center; } .logo { height: 200rpx; width: 200rpx; margin-top: 200rpx; margin-left: auto; margin-right: auto; margin-bottom: 50rpx; } .text-area { display: flex; justify-content: center; } .title { font-size: 36rpx; color: #8f8f94; } </style>
getters
- Getters類似于組件中的計算屬性
- Getters 只是幕后的 computed 屬性,因此無法向它們傳遞任何參數(shù)。 但是,您可以從 getter 返回一個函數(shù)以接受任何參數(shù)
<!-- getter的使用 --> <div>乘2: {{ userInfoStore.doubleAge }}</div> <div>加一: {{ userInfoStore.addOneAge }}</div> <div>返回一個函數(shù)查找id為1的愛好: {{ userInfoStore.returnFunction(1) }}</div>
actions
- Actions 相當于組件中的 methods。它們可以使用
defineStore()
中的actions
屬性定義,并且它們非常適合定義業(yè)務邏輯 - Actions支持異步操作的,可以編寫異步函數(shù)
<!-- action的使用 --> <button @click="add">非異步</button> <button @click="getList">異步</button> // 調用action中的方法 const add = () => { userInfoStore.addAge(5) } //調用異步方法 const getList = () => { userInfoStore.getList() }
模塊的持久化配置
/** 持久化使用方法1 * 當前模塊所有數(shù)據(jù)都進行持久化 * 使用localStorage進行存儲 * 默認將id作為storage中的key * 使用JSON.stringify / JSON.parse進行序列化/反序列化 */ persist: true, /** 持久化使用方法2 * key:存儲名稱 * storage:存儲方式 * path:用于指定state中哪些數(shù)據(jù)需要被持久化,[]表示不持久化任何狀態(tài),undefined或null表示持久化整個state */ persist: { key: 'piniaStore', //存儲名稱 storage: sessionStorage, // 存儲方式 paths: ['userName','obj'], //指定存儲的數(shù)據(jù) }, /** 持久化使用方法3*/ `userName` 值將保存在 `localStorage` 中, `obj` 值將保存在 `sessionStorage` 中。 `age` 沒有被持久化 persist:[ { pick:["userName"], storage:localStorage }, { pick:["obj"], storage:sessionStorage } ],
在uniapp中使用持久化插件
// store/index.js import { createPinia } from "pinia"; import { createPersistedState } from "pinia-plugin-persistedstate"; export function setupStore(app) { const pinia = createPinia(); pinia.use(createPersistUni()); //使用持久化存儲插件 app.use(pinia); } /** * @description 自定義pinia持久化API存儲方式為uni */ // 應用于所有模塊,如在特定模塊設置則寫到對應模塊 function createPersistUni() { return createPersistedState({ storage: { getItem: uni.getStorageSync, setItem: uni.setStorageSync, }, }); } export * from "./modules/user";
// store/moddules/user.js ...... persist: true, // 是否開啟持久化(當前模塊所有數(shù)據(jù)都進行持久化) // 配置持久化 persist: { pick: ["userName"], }, // 配置此模塊的持久化存儲方式 persist: { storage: { // 修改存儲方式 getItem: uni.getStorageSync, setItem: uni.setStorageSync }, key: 'userInfo', // 本地存儲key值 pick: ['obj.money', 'age'] // 指定持久化的數(shù)據(jù),不寫默認持久化整個state }
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue實現(xiàn)手機號、驗證碼登錄(60s禁用倒計時)
這篇文章主要介紹了Vue實現(xiàn)手機號、驗證碼登錄(60s禁用倒計時),幫助大家更好的理解和使用vue,感興趣的朋友可以了解下2020-12-12vue.js實現(xiàn)帶日期星期的數(shù)字時鐘功能示例
這篇文章主要介紹了vue.js實現(xiàn)帶日期星期的數(shù)字時鐘功能,涉及vue.js基于定時器的日期時間運算與數(shù)值操作相關使用技巧,需要的朋友可以參考下2018-08-08