在 Vue 3 的 Composition API 裡,Composable 函式是一種把可重複使用的邏輯抽取出來的方式。先來看看一個範例:
// composables/useCounter.js
import { ref } from 'vue'
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
const increment = () => count.value++
const decrement = () => count.value--
return {
count,
increment,
decrement,
}
}
<script setup>
import { useCounter } from '@/composables/useCounter'
const { count, increment, decrement } = useCounter(5)
</script>
<template>
<div>
<p>目前數字:{{ count }}</p>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
</div>
</template>
Composable 是一個函式。每次呼叫這個函式,就會「建立一份新的資料(state)」 → 獨立狀態。
如果你把 state 放在函式外層,那所有呼叫這個 composable 的元件,會共用同一份狀態 → 共享狀態。
獨立狀態
// useCounter.js
import { ref } from 'vue'
export function useCounter() {
const count = ref(0) // 每次呼叫 useCounter() 都會重新建立
const inc = () => count.value++
return { count, inc }
}
假設 A、B 兩個元件都呼叫 useCounter(),它們各自有自己的 count 互不影響。
共享狀態
// useCounter.js
import { ref } from 'vue'
// 注意:放在函式外層
const count = ref(0)
export function useCounter() {
const inc = () => count.value++
return { count, inc }
}
不管元件怎麼呼叫 useCounter(),看到的都是同一個 count。
看到 composable 我第一個浮出的疑問是,那它和 component 的差別在哪裡勒,都是將東西獨立出來
Component: 抽出畫面 + 行為
Composable: 抽出邏輯