0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【 Vue.js 】piniaの「storeToRefs」とは

Posted at

ポートフォリオ用アプリにpiniaを使っていますが、まだ無知に等しい状態なので備忘録です。

storeToRefsとは

Piniaのユーティリティ関数。リアクティブ性を担保しながら、Storeからプロパティを参照するために使用します。

〇ユーティリティ関数とは
再利用可能な処理として簡単に呼び出せるように作成される小さな関数のことです。ユーティリティ関数を使用するkとでコードが整理され、可読性とメンテナンス性が向上します。

src/store/food.js
import { defineStore } from "pinia";
import { allFoods } from "../http/food-api";
import { ref } from "vue";

export const useFoodStore = defineStore('foodStore', () => {
    const foods = ref([]);

    const fetchAllFoods = async () => {
        const { data } = await allFoods();
        foods.value = data.data;
    }

    return {
        foods,
        fetchAllFoods,
    };
});
src/pages/Foods/NewFoodPage.vue
<script setup>
import { onMounted, ref, computed } from 'vue';
import { storeToRefs } from 'pinia';
import { useFoodStore } from '../../stores/food';
import api from "../../http/api";

const foodStore = useFoodStore()
const { foods } = storeToRefs(foodStore)
const { fetchAllFoods } = foodStore

onMounted(async () => {
    await fetchAllFoods()
})

</script>

また、storeToRefsを使うで.valueを使って値を取得できるようになります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?