iT邦幫忙

2025 iThome 鐵人賽

DAY 12
0
Vue.js

從零開始的Vue之旅系列 第 12

語法介紹Part5-components

  • 分享至 

  • xImage
  •  

今天我們來談談components組件

components
components : 組件,可將網頁的使用者介面(UI)拆成獨立,可重複使用的程式碼區塊。
組件包含
script(邏輯/資料)、template(HTML結構)、style(樣式)

為何使用組件

  • 獨立性 : 每個組件都有自己的結構、邏輯和樣式,這表示可以在不影響其他組件的情況下開發和修改特定組件。
  • 可重複使用 : 可在網頁任何地方重複使用,保持介面的一致性,也減少程式碼的重複性。
  • 可組合性 : 可依照自身需求將各個組件組合起來,例如將多個「產品卡片」組件組合到一個「產品列表」組件中

利用組件可以讓程式碼更容易理解和維護,多人開發時可以各自負責不同組件,再組合起來,增加效率及統整性。
範例
App.vue

<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'

const greeting = ref('Hello from parent')
</script>

<template>
  <ChildComp />
</template>

ChildComp.vue

<script setup>
const props = defineProps({
  msg: String
})
</script>

<template>
  <h2>{{ msg || 'No props passed yet' }}</h2>
</template>

父組件可在模板中渲染子組件,要使用組件時需要先將組件引入,例如
import ChildComp from './ChildComp.vue' 在App.vue引入ChildComp.vue將其取名為ChildComp。
這樣就能在模板中使用組件 <ChildComp />並執行子組件ChildComp.vue的程式

props
props:屬性,子組件可透過props接收從父組件傳來的動態數據
props特點:可以傳遞多種資料型態,例如數字、字串、物件、陣列、函數,子組件只能接收父組件傳來的數據,不能直接修改。
<ChildComp :msg="greeting" />中的 msg就是子組件的props名稱,: 是v-bind的縮寫,greeting是父組件的變數。將greeting傳給子組件的msg,並執行ChildComp.vue

透過props可將父組件的資料傳給子組件,那子組件該如何向父組件觸發事件呢?這時可藉由emit來達成。
範例
App.vue

import { ref } from 'vue'
import ChildComp from './ChildComp.vue'

const childMsg = ref('No child msg yet')
</script>

<template>
  <ChildComp @response="(msg) => childMsg = msg" />
  <p>{{ childMsg }}</p>
</template>

import ChildComp from './ChildComp.vue' 建立一個響應式變數,初始值是'No child msg yet'
<p>{{ childMsg }}</p>當子組件傳回訊息後顯示該訊息
<ChildComp @response="(msg) => childMsg = msg" />父組件監聽子組件的response事件
子組件emit('response', 'hello from child')接收到參數msg

ChildComp.vue

<script setup>
const emit = defineEmits(['response'])

emit('response', 'hello from child')
</script>

<template>
  <h2>Child component</h2>
</template>

defineEmits(['response'])定義子組件發送的事件名稱response
emit('response', 'hello from child')子組件觸發事件把'hello from child'發送出去

總結就是
父組件用props 傳資料給子組件
子組件用emits 傳回資料給父組件


好的今天先到這裡,明天繼續,各位明天見~


上一篇
語法介紹Part4-watch
系列文
從零開始的Vue之旅12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言