一 基本使用
1 項目安裝pinia
npm i pinia
2 main.js中導入
import { createPinia } from 'pinia';
// 創(chuàng)建pinia實例
const pinia = createPinia()
app.use(pinia);
3 新建一個文件用來管理狀態(tài)
在src下新建store文件夾,在store文件夾下新建一個js文件如demoStore.js,我用useDemoStore.js來命名
import { defineStore } from "pinia";
//defineStore兩個參數(shù):1模塊名稱 2對象包含state函數(shù)、getters和actions對象
export const useDemoStore = defineStore('demo',{
state:()=>{
return {
name:"張三",
age:1
}
},
getters:{},
actions:{}
})
4 訪問store中的狀態(tài)
步驟1 :導入store, 調(diào)用useStore得到響應式對象store
步驟2 :獲取狀態(tài)(兩種方式)
<script setup>
import { ref } from "vue";
import { useDemoStore } from "@/store/useDemoStore";
import { storeToRefs } from "pinia";
const store = useDemoStore();
//方式1:直接通過store.xxx獲取
console.log(store.phone);
//方式2 : 解構(gòu)使用, 需要使用鉤子storeToRefs, 不然解構(gòu)后的變量不具備響應式
// let { name, msg } = store; // 不具備響應式
let { name, msg } = storeToRefs(store);
二 修改狀態(tài)
方法1 :通過$patch直接修改store狀態(tài)
import { useDemoStore } from "@/store/useDemoStore";
const store = useDemoStore();
//調(diào)用store.$patch
store.$patch((state) => {
state.msg = "哈哈哈哈";
});
方法2:通過action
1 編寫自定義文件useDemoStore.js中的action
actions:{
changeName(newName){
this.name = newName;
}
}
2 調(diào)用action中定義的方法
import { useDemoStore } from "@/store/useDemoStore";
const store = useDemoStore();
//調(diào)用actions中的方法
store.changeName("李四");
三 使用getters
getters: {
msg2(state) {
return state.msg.toUpperCase();
}
}
四 pinia持久化
1 安裝
npm install pinia-plugin-persist --save
2 在main.js導入使用
import piniaPluginPersist from 'pinia-plugin-persist';
const pinia = createPinia();
pinia.use(piniaPluginPersist);
3 緩存相關(guān)設(shè)置
export const useDemoStore = defineStore("demo", {
//緩存配置
persist: {
enabled: true,
strategies: [
{
// 緩存的模塊名稱,對應緩存中的密鑰key
key: "demo",
// 保存位置,默認保存在sessionStorage
storage: localStorage,
// 緩存哪些狀態(tài)
paths: ["name"]
}
]
},
// ....
});