LoginSignup
3
0

概要

Pinia は、Vue.js アプリケーションのステート管理をしてくれるライブラリです。従来の Vuex に比べてシンプルになったみたいですので、この記事では、Pinia の導入とステート管理の基本について解説します。

1. Pinia のインストール

まず、Pinia をプロジェクトにインストールします。

npm install pinia

2. Pinia の初期化

次に、Pinia を Vue アプリケーションに初期化します。

import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';

const app = createApp(App);
app.use(createPinia());
app.mount('#app');

このコードでは、createPinia 関数を使用して Pinia インスタンスを作成し、use メソッドを使用して Vue アプリケーションに登録しています。

3. ストアの作成

Pinia を使用してステートを管理するには、ストアを作成する必要があります。ストアは、アプリケーションのデータとロジックをカプセル化するオブジェクトです。

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  getters: {
    doubleCount: (state) => state.count * 2
  },
  actions: {
    increment() {
      this.count++
    }
  }
})

このコードでは、defineStore 関数を使用して counter という名前のストアを作成します。ストアには、stategettersactions が含まれます。

  • state: ストアに格納されるデータ
  • getters: state のデータを基に、計算されたプロパティを作成するために使用
  • actions: ストア内のデータを変更する関数

4. ストアの使用

ストアは、Vue コンポーネントからアクセスできます。

<script setup>
import { useCounterStore } from '../stores/counter'
import { computed } from 'vue'

const counterStore = useCounterStore()
const count = computed(() => counterStore.count)
const doubleCount = computed(() => counterStore.doubleCount)
const increment = () => counterStore.increment()
</script>

<template>
  <div>
    <p>カウント: {{ count }}</p>
    <p>2 倍のカウント: {{ doubleCount }}</p>
    <button @click="increment">カウント</button>
  </div>
</template>

このコードでは、useCounterStore 関数を使用してストアにアクセスし、count プロパティと increment メソッドを定義しています。computed は、count プロパティの変化に応じて自動的に更新される計算プロパティを作成します。

まとめ

vuexはまだ使えますが今後新しい機能は提供されないみたいなので、piniaを扱い方を学習してみました。
シンプルでわかりやすい点やCompositionAPI、typeScriptなどとも互換性があるため扱いやすかったです。

3
0
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
0