Open4

Composables

seiya2130seiya2130

サンプル

カウントのビジネスロジックをuseCounter.tsに切り出すことで、Counter.vueは表示に関する処理だけを書けば良いため、SFCがシンプルになる

useCounter.ts
import { type Ref, ref } from 'vue';

/**
 * useCounter カスタムフック
 * 
 * @param {number} initialValue - カウンターの初期値 (デフォルトは0)
 * @returns {object} - カウンターの値、インクリメント関数、デクリメント関数を含むオブジェクト
 * @property {Ref<number>} count - カウンターの現在の値を保持するリアクティブな参照
 * @property {function} increment - カウンターの値を1増やす関数
 * @property {function} decrement - カウンターの値を1減らす関数
 */
export const useCounter = (initialValue: number = 0): {
    count: Ref<number>,
    increment: () => void,
    decrement: () => void,
} => {
    const count = ref<number>(initialValue);

    /**
     * カウンターの値を1増やす
     */
    const increment = (): void => {
        count.value++;
    }

    /**
     * カウンターの値を1減らす
     */
    const decrement = (): void => {
        count.value--;
    }

    return { count, increment, decrement }
}
Counter.vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
  </div>
</template>

<script setup lang="ts">
import { useCounter } from './helpers/userCounter';

const props = defineProps({
  initialCount: Number
});

const { count, increment, decrement } = useCounter(props.initialCount);

</script>
App.vue
<template>
  <Counter :initial-count='num1'></Counter>
  <Counter :initial-count='num2'></Counter>
</template>

<script setup lang="ts">
import Counter from './Counter.vue';

const num1 = 100;
const num2 = 200;

</script>

https://github.com/seiya2130/VueLab/pull/1

seiya2130seiya2130

各ファイルの責務

  • vue
    • データの表示
    • イベントハンドラ
    • コンポーネント間のデータの受け渡し
    • composablesやmodelのメソッド呼び出し
  • composables
    • ビジネスロジック
    • API呼び出し
  • model
    • データの属性・振る舞いを定義
    • データの状態管理