50
Vue 3 學習之旅
高級特性

Day 50: 自訂組合式函數 (Composables)

·6 分鐘閱讀·組合式函數

摘要

自訂組合式函數 (Composable) 是一個利用 Vue 組合式 API 來封裝和複用「有狀態邏輯」的函數。它是一種組織和共享程式碼的模式,是組合式 API 最強大的特性之一。

定義與說明

一個組合式函數通常是一個以 use 開頭的函數(例如 useMouse、useFetch)。它可以在內部使用 ref、computed、watch 等組合式 API,並回傳一個包含了響應式狀態和方法的物件。任何元件都可以呼叫這個函數,來獲取一份獨立的、可複用的邏輯。

實作範例

自訂組合式函數示例
// composables/useCounter.js
import { ref, readonly } from 'vue';
export function useCounter() {
  const count = ref(0);
  function increment() { count.value++; }
  return {
    count: readonly(count), // 回傳唯讀的 count
    increment
  };
}

<!-- MyComponent.vue -->
<script setup>
import { useCounter } from './composables/useCounter.js';
// 在元件中使用組合式函數
const { count, increment } = useCounter();
</script>
<template>
  <button @click="increment">計數: {{ count }}</button>
</template>

結論

組合式函數是 Vue 3 中實現邏輯複用的最佳方式。它徹底解決了 Mixins 的各種弊端(如命名衝突、來源不明),讓程式碼的組織更清晰、彈性更高。

組合式函數 Composables 邏輯複用