pinia的使用跟vuex很像,去除了很多沒用的api,寫法有兩種,一種老式的選項式api還有一種組合式api,用哪種根據自己喜好來,以下示例為組合式api
更多教程參考官網:pinia官網https://pinia.vuejs.org/zh/
安裝
npm install pinia
配置
import { createPinia } from 'pinia';
import persisted from "pinia-plugin-persistedstate";//持久化插件
import App from './App.vue'
const pinia = createPinia();
const app = createApp(App)
app.use(pinia.use(persisted));//使用pinia以及pinia持久化插件
新建store文件夾=>index.js
引入defineStore方法穿件一個store,主要接收三個參數
參數一:store的唯一key值
參數二:數據存儲區以及方法,
參數三:持久化配置(將數據放緩存持久保存)
import {defineStore
} from "pinia"
import {ref
} from "vue"// 首頁屬性
export const usehomeStore = defineStore('storeKey', () => {let menuState = ref(false)//菜單展開狀態const testData = ref('測試');function changeMenuStateFn() {menuState.value = !menuState.value}return {menuState,testData,changeMenuStateFn,}
},
{persist:{enabled:true,//是否開啟持久化,對象形式不寫默認為開啟key:'menuShowState',//存儲時候的key值,默認為defineStore的keystorage:"sessionStorage",//存儲類型,默認localStoragepaths:['menuState'],//需要持久化的數據,默認全部serializer:{deserialize:()=>{console.log('ooo');},serialize:()=>{console.log('ppp');},},//序列化方法,默認為JSON.parse與JSON.stringifybeforeRestore: (ctx) => {console.log(`即將恢復 '${ctx.store.$id}'`)},afterRestore: (ctx) => {console.log(`剛剛恢復完 '${ctx.store.$id}'`)},}
}
)
頁面使用:
使用的時候記得使用一下,因為向外暴露的是一個方法,所以需要調用一下才能獲取到值,因為在store里面已經使用ref響應過了 所以無需用ref定義,直接在頁面使用即是響應式數據,
注意:此處盡量不要解構,解構會丟失響應式,如果一定要解構請使用storeToRefs,
此方法需要從pinia中導入,
使用示例:示例來自官網
<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()
// `name` 和 `doubleCount` 是響應式的 ref
// 同時通過插件添加的屬性也會被提取為 ref
// 并且會跳過所有的 action 或非響應式 (不是 ref 或 reactive) 的屬性
const { name, doubleCount } = storeToRefs(store)
// 作為 action 的 increment 可以直接解構
const { increment } = store
</script>
import {usehomeStore,usePublic} from "@/store/index.js"
const homeStore = usehomeStore();
const publicStore = usePublic();
<el-aside class="aside" :width="homeStore.menuState?'60px':'200px'">