LoginSignup
3
4

More than 1 year has passed since last update.

【pinia-plugin-persistedstate】PiniaでのStore永続化

Last updated at Posted at 2022-11-14

ページのリロードでstoreのデータが消えてしまわないよう、storeの状態管理を永続化したい場合はライブラリを利用することで簡単に実現可能です。

Pinia対応のライブラリはいくつかあるようです。

今回は最もfavoriteと利用者が多く、更新頻度も高そうなpinia-plugin-persistedstateを採用します。

環境構築

前提

  • Vue3
  • Vite
  • TypeSciprt
  • Pinia

上記の環境構築については、記事にする予定

方法

  1. インストール

    yarn add pinia-plugin-persistedstate
    
  2. 設定

    main.tsにプラグインを追加します。

    import { createApp } from "vue";
    import App from "./App.vue";
    import { createPinia } from "pinia";
    import { createPersistedState } from "pinia-plugin-persistedstate"; // 追加
    
    const pinia = createPinia(); // 追加
    pinia.use(createPersistedState()); // 追加
    
    createApp(App).use(pinia).mount("#app"); // 修正
    
  3. storeを永続化

    永続したいstoreで defineStore() の新しいオプションに persist:true を設定します。

    // src/stores/counter.js
    import { defineStore } from "pinia";
    import { ref } from "vue";
    
    export const useCounterStore = defineStore(
      "counter",
      () => {
        const count = ref(0);
        function increment() {
          count.value++;
        }
        return { count, increment };
      },
      {
        persist: true,
      }
    );
    

    リロードしてもstoreのデータが消えなくなったことが確認できます。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4