2025-03-27- Vue 的事件課程作業

2025-03-27- Vue 的事件課程作業

Vue 的事件課程作業 👍
我們會分成兩部分:


✅ 課程目標

學習怎麼 設計元件事件(如 @click),並且可以設定多個屬性來自訂元件外觀與行為。


🧱 作業需求總結

請建立一個 MyButton.vue 元件,支援以下 props 和功能:

Prop / Event 功能說明
color 背景色
textColor 文字顏色
label 按鈕文字內容
size 按鈕大小(如 small、medium、large)
round 是否圓角
square 是否方形
@click 點擊事件

並且在 App.vue 中引入這個元件,做多個使用示範。


✨ 1. 建立 MyButton.vue 元件

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
<!-- MyButton.vue -->
<template>
<button
:class="[
'my-button',
sizeClass,
{ round, square }
]"
:style="buttonStyle"
@click="$emit('click')"
>
{{ label }}
</button>
</template>

<script setup>
import { computed } from 'vue'

defineProps({
color: { type: String, default: '#1976d2' },
textColor: { type: String, default: '#ffffff' },
label: { type: String, default: 'Click Me' },
size: { type: String, default: 'medium' }, // 'small' | 'medium' | 'large'
round: { type: Boolean, default: false },
square: { type: Boolean, default: false }
})

const props = defineProps()

const sizeClass = computed(() => {
return {
small: 'btn-sm',
medium: 'btn-md',
large: 'btn-lg'
}[props.size] || 'btn-md'
})

const buttonStyle = computed(() => ({
backgroundColor: props.color,
color: props.textColor,
}))
</script>

<style scoped>
.my-button {
border: none;
cursor: pointer;
padding: 0.5em 1em;
font-size: 1rem;
transition: 0.2s;
}

.btn-sm {
padding: 0.3em 0.6em;
font-size: 0.8rem;
}

.btn-md {
padding: 0.5em 1em;
font-size: 1rem;
}

.btn-lg {
padding: 0.75em 1.5em;
font-size: 1.2rem;
}

.round {
border-radius: 999px;
}

.square {
border-radius: 0;
}
</style>

💡 2. App.vue 使用範例

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
<!-- App.vue -->
<template>
<div>
<h2>🧪 MyButton.vue 測試</h2>

<MyButton
label="紅色圓角大按鈕"
color="red"
textColor="white"
size="large"
:round="true"
@click="handleClick('紅色按鈕')"
/>

<MyButton
label="藍色方形中按鈕"
color="blue"
textColor="white"
size="medium"
:square="true"
@click="handleClick('藍色按鈕')"
/>

<MyButton
label="小按鈕"
color="green"
textColor="black"
size="small"
@click="handleClick('綠色小按鈕')"
/>
</div>
</template>

<script setup>
import MyButton from './MyButton.vue'

function handleClick(name) {
alert(`你點擊了 ${name}`)
}
</script>

🛠️ 測試方式

你可以在 Vue SFC Playground 貼上這兩段程式碼(分別放在 App.vueMyButton.vue),就可以看到效果。