全书目录

第三篇:Vue 完全指南 —— 新城区商业街宇宙

第十二章:组合式函数 —— 把营业 SOP 抽成标准手册

1 分钟 47 字 第 82 / 962 个阅读单元

Vue 把逻辑复用的官方名字叫 Composables

ts
// composables/useShopStatus.ts
import { ref, computed } from 'vue';

export function useShopStatus(initialRevenue = 0) {
  const revenue = ref(initialRevenue);
  const cost = ref(0);

  const profit = computed(() => revenue.value - cost.value);
  const status = computed(() => (profit.value >= 0 ? '盈利' : '亏损'));

  function addRevenue(amount: number) {
    revenue.value += amount;
  }

  return {
    revenue,
    cost,
    profit,
    status,
    addRevenue,
  };
}
vue
<script setup lang="ts">
import { useShopStatus } from '@/composables/useShopStatus';

const shop = useShopStatus(1000);
</script>

<template>
  <p>利润:{{ shop.profit }}</p>
  <p>状态:{{ shop.status }}</p>
  <button @click="shop.addRevenue(100)">新增收入</button>
</template>

它很像商业街里的标准营业手册