今天我們來談談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'])
定義子組件發送的事件名稱responseemit('response', 'hello from child')
子組件觸發事件把'hello from child'發送出去
總結就是
父組件用props 傳資料給子組件
子組件用emits 傳回資料給父組件
好的今天先到這裡,明天繼續,各位明天見~