iT邦幫忙

2025 iThome 鐵人賽

DAY 12
0
Vue.js

Vue 新手學習紀錄系列 第 12

Day 12 | Composable 函式: 模組化程式邏輯

  • 分享至 

  • xImage
  •  

在 Vue 3 的 Composition API 裡,Composable 函式是一種把可重複使用的邏輯抽取出來的方式。先來看看一個範例:

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>
  • 將邏輯搬到 useXXX.js 的檔案中,以便重複使用

共享與獨立狀態

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。

Component vs. Composable

看到 composable 我第一個浮出的疑問是,那它和 component 的差別在哪裡勒,都是將東西獨立出來
Component: 抽出畫面 + 行為

  • 主要管理畫面 (template) + 行為 (script)
  • 適合拆出 UI 元件,如: 按鈕、表單、列表等等

Composable: 抽出邏輯

  • 主要用處為管理邏輯 (state + function),不管畫面
  • 適合抽出邏輯功能,如: 計數器邏輯、API 請求、登入狀態等等

上一篇
Day 11|Composition API 入門
系列文
Vue 新手學習紀錄12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言