關(guān)于pinia的使用和持久化方式(pinia-plugin-persistedstate)
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) //使用持久化存儲(chǔ)插件
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中 使用另一個(gè)getter this指向當(dāng)前存儲(chǔ)庫
addOneAge() {
return this.doubleAge + 1;
},
//返回一個(gè)函數(shù)
returnFunction(state) {
return function (id) {
return state.hobby.find((item) => item.id == id);
};
},
},
//可以通過this訪問整個(gè)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在它被使用之前是不會(huì)創(chuàng)建的,我們可以通過調(diào)用use函數(shù)來使用Store。
- 一旦 store 被實(shí)例化,你就可以直接在 store 上訪問 state、getters 和 actions 中定義的任何屬性
- store 是一個(gè)用reactive 包裹的對(duì)象,這意味著不需要在getter 之后寫.value,但是,就像setup 中的props 一樣,我們不能對(duì)其進(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 }}個(gè)</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)式
// 一個(gè)一個(gè)修改
const editPiniaHandler = () => {
userInfoStore.userName = "小明";
userInfoStore.age += 1;
};
//使用$patch方法 以對(duì)象的形式一次性修改
const editAll = () => {
userInfoStore.$patch({
userName: "鴨蛋",
age: 21,
});
};
// $state 替換 state 為新對(duì)象
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 返回一個(gè)函數(shù)以接受任何參數(shù)
<!-- getter的使用 -->
<div>乘2: {{ userInfoStore.doubleAge }}</div>
<div>加一: {{ userInfoStore.addOneAge }}</div>
<div>返回一個(gè)函數(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)行存儲(chǔ)
* 默認(rèn)將id作為storage中的key
* 使用JSON.stringify / JSON.parse進(jìn)行序列化/反序列化
*/
persist: true,
/** 持久化使用方法2
* key:存儲(chǔ)名稱
* storage:存儲(chǔ)方式
* path:用于指定state中哪些數(shù)據(jù)需要被持久化,[]表示不持久化任何狀態(tài),undefined或null表示持久化整個(gè)state
*/
persist: {
key: 'piniaStore', //存儲(chǔ)名稱
storage: sessionStorage, // 存儲(chǔ)方式
paths: ['userName','obj'], //指定存儲(chǔ)的數(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()); //使用持久化存儲(chǔ)插件
app.use(pinia);
}
/**
* @description 自定義pinia持久化API存儲(chǔ)方式為uni
*/
// 應(yīng)用于所有模塊,如在特定模塊設(shè)置則寫到對(duì)應(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"],
},
// 配置此模塊的持久化存儲(chǔ)方式
persist: {
storage: { // 修改存儲(chǔ)方式
getItem: uni.getStorageSync,
setItem: uni.setStorageSync
},
key: 'userInfo', // 本地存儲(chǔ)key值
pick: ['obj.money', 'age'] // 指定持久化的數(shù)據(jù),不寫默認(rèn)持久化整個(gè)state
}總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
element中table操作按鈕展示與折疊的實(shí)現(xiàn)示例
因?yàn)殡S著功能的增多,table操作欄中的功能按鈕增多,這時(shí)候就需要折疊,本文主要介紹了element中table操作按鈕展示與折疊的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2022-04-04
使用vuex解決刷新頁面state數(shù)據(jù)消失的問題記錄
這篇文章主要介紹了使用vuex解決刷新頁面state數(shù)據(jù)消失的問題記錄,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05
Vue源碼學(xué)習(xí)之?dāng)?shù)據(jù)初始化
這篇文章主要為大家介紹了Vue源碼學(xué)習(xí)之?dāng)?shù)據(jù)初始化實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
vue2.0+vue-router構(gòu)建一個(gè)簡(jiǎn)單的列表頁的示例代碼
這篇文章主要介紹了vue2.0+vue-router構(gòu)建一個(gè)簡(jiǎn)單的列表頁的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-02-02
element-ui中實(shí)現(xiàn)tree子節(jié)點(diǎn)部分選中時(shí)父節(jié)點(diǎn)也選中
這篇文章主要介紹了element-ui中實(shí)現(xiàn)tree子節(jié)點(diǎn)部分選中時(shí)父節(jié)點(diǎn)也選中的方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
解決Vue2?axios發(fā)請(qǐng)求報(bào)400錯(cuò)誤"Error:?Request?failed?with?s
這篇文章主要給大家介紹了關(guān)于如何解決Vue2?axios發(fā)請(qǐng)求報(bào)400錯(cuò)誤"Error:?Request?failed?with?status?code?400"的相關(guān)資料,在Vue應(yīng)用程序中我們通常會(huì)使用axios作為網(wǎng)絡(luò)請(qǐng)求庫,需要的朋友可以參考下2023-07-07
vue數(shù)據(jù)初始化initState的實(shí)例詳解
Vue 實(shí)例在建立的時(shí)候會(huì)運(yùn)行一系列的初始化操作,而在這些初始化操作里面,和數(shù)據(jù)綁定關(guān)聯(lián)最大的是 initState。這篇文章主要介紹了vue數(shù)據(jù)初始化--initState,需要的朋友可以參考下2019-04-04
vue實(shí)現(xiàn)的樹形結(jié)構(gòu)加多選框示例
這篇文章主要介紹了vue實(shí)現(xiàn)的樹形結(jié)構(gòu)加多選框,結(jié)合實(shí)例形式分析了在之前遞歸組件實(shí)現(xiàn)vue樹形結(jié)構(gòu)的基礎(chǔ)之上再加上多選框功能相關(guān)操作技巧,需要的朋友可以參考下2019-02-02

