1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| <template> <div> <h1>小型分帳系統</h1> <!-- 輸入參與者 --> <div> <h2>參與者</h2> <input v-model="newParticipant" placeholder="輸入成員名稱" /> <button @click="addParticipant">新增</button> <ul> <li v-for="person in participants" :key="person"> {{ person }} <button @click="removeParticipant(person)">移除</button> </li> </ul> </div>
<!-- 記錄費用 --> <div> <h2>新增費用</h2> <input v-model="newExpense.description" placeholder="描述" /> <input v-model.number="newExpense.amount" type="number" placeholder="金額" /> <select v-model="newExpense.payer"> <option v-for="person in participants" :key="person" :value="person">{{ person }}</option> </select> <div> <label v-for="person in participants" :key="person"> <input type="checkbox" :value="person" v-model="newExpense.participants" /> {{ person }} </label> </div> <button @click="addExpense">記錄費用</button> </div>
<!-- 顯示分帳結果 --> <div> <h2>結果</h2> <ul> <li v-for="(balance, person) in balances" :key="person"> {{ person }}: {{ balance > 0 ? `應收 ${balance}` : `應付 ${-balance}` }} </li> </ul> </div> </div> </template>
<script> import { ref, computed } from "vue";
export default { setup() { const participants = ref([]); const expenses = ref([]); const newParticipant = ref(""); const newExpense = ref({ description: "", amount: 0, payer: "", participants: [], });
const addParticipant = () => { if (newParticipant.value && !participants.value.includes(newParticipant.value)) { participants.value.push(newParticipant.value); newParticipant.value = ""; } };
const removeParticipant = (person) => { participants.value = participants.value.filter((p) => p !== person); };
const addExpense = () => { if ( newExpense.value.description && newExpense.value.amount > 0 && newExpense.value.payer && newExpense.value.participants.length ) { expenses.value.push({ ...newExpense.value }); newExpense.value = { description: "", amount: 0, payer: "", participants: [] }; } };
const balances = computed(() => { const result = {}; participants.value.forEach((person) => (result[person] = 0)); expenses.value.forEach((expense) => { const share = expense.amount / expense.participants.length; expense.participants.forEach((person) => (result[person] -= share)); result[expense.payer] += expense.amount; }); return result; });
return { participants, expenses, newParticipant, newExpense, addParticipant, removeParticipant, addExpense, balances, }; }, }; </script>
|