Skip to content
sumnail

Stateのリセット

created at : 2024/08/31

Pinia
Vue3

状態管理を使用することで、ページ間(コンポーネント間)で State を共有することができます。

それぞれのページのサンプルは、同じ store を使用しているので増減が連動することが確認できます。

State のリセット

状態管理を使用すると、State を初期値に戻す処理が必要になる場合があります。

Pinia では、$reset() を使って State を初期値に戻すことができます。

リセットの使い方

State を初期値に戻す方法を紹介します。

注意

$reset() は、Option Stores で定義した State に対してのみ使用できます。 Setup Stores で定義した State は、store 内で定義が必要になります!

sample

リセットボタンを押下するとカウンターがリセットされます。

Counter: 0

サンプルコードは以下の通りです。

vue
<template>
  <div>
    <p>Counter: {{ counter }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
    <button @click="reset">Reset</button>
  </div>
</template>

<script setup lang="ts">
import { useCounter } from "../../../.vitepress/theme/stores/counter";
import { storeToRefs } from "pinia";

const store = useCounter();
const { counter } = storeToRefs(store);
const { increment, decrement } = useCounter();

const reset = () => {
  store.$reset();
};
</script>

<style scoped>
p {
  font-size: 20px;
}
button {
  margin: 8px;
  padding: 8px 16px;
  background-color: var(--secondary-color);
  border-radius: 8px;
}
</style>

store の定義

store の定義は以下の通りです。

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

export const useCounter = defineStore("counter", () => {
  const counter = ref(0);
  const doubleCounter = computed(() => counter.value * 2);
  const increment = () => {
    return counter.value++;
  };
  const decrement = () => {
    return counter.value--;
  };

  function $reset() {
    counter.value = 0;
  }

  return { counter, doubleCounter, increment, decrement, $reset };
});

まとめ

Pinia の State のリセット方法を紹介しました。

参考