關(guān)于pinia的使用和持久化方式(pinia-plugin-persistedstate)
更新時間:2025年02月17日 14:28:28 作者:堅(jiān)定信念,勇往無前
本文介紹了Pinia的使用方法,包括安裝和配置插件pinia-plugin-persistedstate,以及在項(xiàng)目中創(chuàng)建和使用Store模塊,同時,還講解了Pinia的state、getters和actions的使用,并提供了在uniapp中使用持久化插件的總結(jié)
pinia的使用和持久化(pinia-plugin-persistedstate)
安裝插件
- npm install pinia
- npm install pinia-plugin-persistedstate
文件配置
方法一
- 在store/index.js文件中進(jìn)行初始化配置
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文件中進(jìn)行配置
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: { // 類似于計(jì)算屬性,參數(shù)state指向defineStore下的state doubleAge(state) { return state.age * 2; }, //在getter中 使用另一個getter this指向當(dāng)前存儲庫 addOneAge() { return this.doubleAge + 1; }, //返回一個函數(shù) returnFunction(state) { return function (id) { return state.hobby.find((item) => item.id == id); }; }, }, //可以通過this訪問整個store實(shí)例的所有操作,支持異步操作 actions: { //非異步操作 addAge(e) { console.log("接受的數(shù)據(jù)", e); //e是外部調(diào)用方法傳遞的參數(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)建的,我們可以通過調(diào)用use函數(shù)來使用Store。
- 一旦 store 被實(shí)例化,你就可以直接在 store 上訪問 state、getters 和 actions 中定義的任何屬性
- store 是一個用reactive 包裹的對象,這意味著不需要在getter 之后寫.value,但是,就像setup 中的props 一樣,我們不能對其進(jìn)行解構(gòu)
<template> <div class="content"> <div>我叫{{ userName }},今年{{ age }}歲</div> <div>財(cái)富有{{ obj.money }}萬元</div> <div>其他資產(chǎn)有{{ obj.house || obj.friend }}個</div> <div>愛好有</div> <div v-for="item in hobby" :key="item.id"> <div>{{ item.name }}</div> </div> <button @click="editPiniaHandler">點(diǎn)擊修改</button> <button @click="editAll">點(diǎn)擊修改全部</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轉(zhuǎn)換 const userInfoStore = useUserStore() // const { username, age, like, hobby } = userInfoStore //直接結(jié)構(gòu)賦值 不是響應(yīng)式 const { userName, age, hobby, obj } = storeToRefs(userInfoStore); // 響應(yīng)式 // 一個一個修改 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類似于組件中的計(jì)算屬性
- 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 相當(dāng)于組件中的 methods。它們可以使用
defineStore()
中的actions
屬性定義,并且它們非常適合定義業(yè)務(wù)邏輯 - Actions支持異步操作的,可以編寫異步函數(shù)
<!-- action的使用 --> <button @click="add">非異步</button> <button @click="getList">異步</button> // 調(diào)用action中的方法 const add = () => { userInfoStore.addAge(5) } //調(diào)用異步方法 const getList = () => { userInfoStore.getList() }
模塊的持久化配置
/** 持久化使用方法1 * 當(dāng)前模塊所有數(shù)據(jù)都進(jìn)行持久化 * 使用localStorage進(jìn)行存儲 * 默認(rèn)將id作為storage中的key * 使用JSON.stringify / JSON.parse進(jìn)行序列化/反序列化 */ 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 */ // 應(yīng)用于所有模塊,如在特定模塊設(shè)置則寫到對應(yīng)模塊 function createPersistUni() { return createPersistedState({ storage: { getItem: uni.getStorageSync, setItem: uni.setStorageSync, }, }); } export * from "./modules/user";
// store/moddules/user.js ...... persist: true, // 是否開啟持久化(當(dāng)前模塊所有數(shù)據(jù)都進(jìn)行持久化) // 配置持久化 persist: { pick: ["userName"], }, // 配置此模塊的持久化存儲方式 persist: { storage: { // 修改存儲方式 getItem: uni.getStorageSync, setItem: uni.setStorageSync }, key: 'userInfo', // 本地存儲key值 pick: ['obj.money', 'age'] // 指定持久化的數(shù)據(jù),不寫默認(rèn)持久化整個state }
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
VUE項(xiàng)目運(yùn)行失敗原因及解決辦法圖解(以vscode為例)
記錄一下踩坑,前幾天從同事手上接手了一個Vue的項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于VUE項(xiàng)目運(yùn)行失敗原因及解決辦法的相關(guān)資料,本文以vscode為例,需要的朋友可以參考下2023-06-06Vue實(shí)現(xiàn)手機(jī)號、驗(yàn)證碼登錄(60s禁用倒計(jì)時)
這篇文章主要介紹了Vue實(shí)現(xiàn)手機(jī)號、驗(yàn)證碼登錄(60s禁用倒計(jì)時),幫助大家更好的理解和使用vue,感興趣的朋友可以了解下2020-12-12vue百度地圖修改折線顏色,添加icon和文字標(biāo)注方式
這篇文章主要介紹了vue百度地圖修改折線顏色,添加icon和文字標(biāo)注方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03Vue3中各種靈活傳遞數(shù)據(jù)的方式小結(jié)
Vue 3 提供了多種數(shù)據(jù)傳遞的方式,讓我們的組件之間可以盡情地交流,接下來,我們就直接一個個來看,這些方式都是怎么工作的,感興趣的小伙伴跟著小編一起來看看吧2024-07-07vue.js實(shí)現(xiàn)帶日期星期的數(shù)字時鐘功能示例
這篇文章主要介紹了vue.js實(shí)現(xiàn)帶日期星期的數(shù)字時鐘功能,涉及vue.js基于定時器的日期時間運(yùn)算與數(shù)值操作相關(guān)使用技巧,需要的朋友可以參考下2018-08-08