LoginSignup
1
0

More than 1 year has passed since last update.

Setupで🍍Pinia.jsを使う

Last updated at Posted at 2022-08-09

0.🍍 初めに

  • この記事はVue.js 3を使うプロジェクトに基づいて作成しました。

1.🍍 インストール

まずはインストールです。
公式サイト

yarn add pinia
# or with npm
npm install pinia

2.🍍 インポート

main.jsまたはmain.tsで🍍をインポートします。

import { createPinia } from 'pinia'

app.use(createPinia())

3.🍍 Storeを作成

まずはsrcフォルダでstoreフォルダを新規作成、
index.tsまたはindex.jsファイルを新規作成、この記事はtsを使っています。
storeで二つのパターン(Options APIComposition API)があります、この記事はもちろんComposition APIパターンのstoreを作ります。

import { ref } from 'vue'
import { defineStore } from 'pinia'


export const useMainStore = defineStore('main', () => {
  // script setupの感じでstoreを書く
  // 値
  const count = ref<number>(1)
  // メソッド
  const increment = ():void => {
    count.value++
  }

  return { count, increment }
})

4.🍍 Storeを使う

App.vueで使う

<template>
  <div>
    count: {{ count }}
    <button @click="increment()">increment</button>
  </div>
</template>

<script lang="ts" setup>
import { storeToRefs } from 'pinia'
import { useMainStore } from '@/store/index'

// hooksの感じで使う
const useMainStore = useMainStore()
const { count, increment } = storeToRefs(useMainStore)

// vueファイルで直接的に値を更新することもできます
count.value = 0
</script>

5.🍍 感想

Vue3に対して、Options APIよりやはり🍍Composition APIのほうが使いやすいと思います。

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