跳至主要內容

持久化插件

刘春龙原创...小于 1 分钟WEB前端Vue3Pinia状态管理教程文档

pinia 有个副作用,就是无法持久化,在浏览器刷新重置之后,会全部回复默认,这时候,我们可以利用插件实现本地持久化存储

安装

npm install --save pinia-plugin-persistedstate

引入持久化插件

import "./assets/main.css";

import { createApp } from "vue";
import { createPinia } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";

import App from "./App.vue";
import router from "./router";

const app = createApp(App);
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
app.use(pinia);
app.use(router);

app.mount("#app");




 





 
 
 



使用持久化插件

import { ref, computed } from "vue";
import { defineStore, acceptHMRUpdate } from "pinia";

export const useCounterStore = defineStore(
  "counter",
  () => {
    const count = ref(1);
    const doubleCount = computed(() => count.value * 2);
    function increment() {
      count.value++;
    }
    const countX3 = () => {
      count.value = count.value * 3;
    };

    return { count, doubleCount, increment, countX3 };
  },
  {
    persist: true,
  }
);

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useCounterStore, import.meta.hot));
}

















 
 
 





此时,回到应用中,进行修该操作,刷新页面查看效果

<template>
  <p>count:{{ count }}</p>
  <p>doubleCount:{{ doubleCount }}</p>
  <button @click="countAdd">count ++</button>
</template>
<script setup lang="ts">
import { useCounterStore } from "@/stores/counter";
import { storeToRefs } from "pinia";
const counterStore = useCounterStore();
const { count, doubleCount } = storeToRefs(counterStore);
const countAdd = () => {
  counterStore.increment();
};
</script>
上次编辑于:
贡献者: 刘春龙
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.7