2025-03-22-JavaScript 系列九:第2課 ── 學習 Vue 的 props 觀念-建立 MyBadge.vue 元件
JavaScript 系列九:第2課 ── 學習 Vue 的 props 觀念-建立 MyBadge.vue
元件
✅ 1. 建立 MyBadge.vue
📁 請在 src/components/
目錄中建立檔案:MyBadge.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
| <!-- src/components/MyBadge.vue --> <template> <span class="badge" :style="badgeStyle" :class="{ rounded }" > {{ label }} </span> </template>
<script setup> import { computed } from 'vue'
const props = defineProps({ color: { type: String, default: '#eee' }, textColor: { type: String, default: '#333' }, label: { type: String, required: true }, rounded: { type: Boolean, default: false } })
const badgeStyle = computed(() => ({ backgroundColor: props.color, color: props.textColor, })) </script>
<style scoped> .badge { display: inline-block; padding: 0.4em 0.8em; font-size: 0.875rem; font-weight: bold; margin: 0.25rem; }
.rounded { border-radius: 999px; } </style>
|
✅ 2. 修改 App.vue
測試元件
📁 請在 src/App.vue
中加入以下內容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <template> <div class="app-container"> <h1>🎯 MyBadge.vue 測試區</h1> <MyBadge label="預設 Badge" /> <MyBadge label="紅底白字" color="#e74c3c" text-color="#fff" /> <MyBadge label="藍底黃字" color="#3498db" text-color="#f1c40f" /> <MyBadge label="圓角綠底白字" color="#2ecc71" text-color="#fff" :rounded="true" /> <MyBadge label="圓角灰底黑字" color="#bdc3c7" text-color="#2c3e50" :rounded="true" /> </div> </template>
<script setup> import MyBadge from './components/MyBadge.vue' </script>
<style scoped> .app-container { padding: 2rem; } </style>
|
✅ 成果說明
label |
color |
text-color |
rounded |
顯示效果 |
預設 |
#eee |
#333 |
否 |
灰底黑字 |
紅底白字 |
#e74c3c |
#fff |
否 |
紅底白字 |
藍底黃字 |
#3498db |
#f1c40f |
否 |
藍底黃字 |
圓角綠底白字 |
#2ecc71 |
#fff |
✅ |
綠底白字,圓角 |
圓角灰底黑字 |
#bdc3c7 |
#2c3e50 |
✅ |
灰底黑字,圓角 |
如果你執行成功,恭喜你 🎉!你已經完成這次課程的 自訂元件開發目標,包含 props、樣式控制與元件引入實作!