安裝:
// npm i pinia --save
// Vue2 需要額外安裝 npm i pinia @vue/composition-api --save
mainn.js
// 引入pinia
import {createPinia,PiniaVuePlugin} from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
Vue.use(PiniaVuePlugin)
const pinia = createPinia()//需要掛載在實(shí)例上
new Vue({
pinia,
render: h => h(App),
}).$mount('#app')
image.png
import { defineStore } from 'pinia' //引入
const useStore = defineStore('storeId', {
// arrow function recommended for full type inference
state: () => {
return {
counter: 0,
name: 'Eduardo',
isAdmin: true,
}
},
getters: {
},
actions: {
increment() {
this.counter++
}
},
// 開啟持久化
persist: {
enabled: true,//開始數(shù)據(jù)緩存
strategies: [
{
// storage: localStorage,//默認(rèn)是sessionStorage
paths: ['counter'],//指定需要持久化存儲(chǔ)的數(shù)據(jù)
}
]
}
})
export default useStore //導(dǎo)出
image.png
頁面使用
image.png
持久化的需要安裝 pinia-plugin-persist 這個(gè)插件 然后上面圖片上面有如何使用