Vue2子元件調用父元件函式 - daniel-qa/Vue GitHub Wiki
Vue2子元件調用父元件函式
- 概念
子元件不直接知道父元件方法
子元件用 $emit('事件名', 資料) 發事件
父元件在模板上用 @事件名="父層方法" 監聽,並執行方法
這樣子元件和父元件解耦,維護性最好。
- 範例
子元件 Child.vue
<template>
<button @click="notifyParent">點我通知父層</button>
</template>
<script>
export default {
methods: {
notifyParent() {
// 發事件給父層,並傳遞資料
this.$emit('on-contact', '子元件的資料')
}
}
}
</script>
- 父元件 Parent.vue
<template>
<div>
<Child @on-contact="toContact" />
</div>
</template>
<script>
import Child from './Child.vue'
export default {
components: { Child },
methods: {
toContact(payload) {
console.log('父元件收到子元件資料:', payload)
// 在這裡做父元件的函式邏輯
}
}
}
</script>
- ****重點
子元件用 $emit('事件名', 資料) → 不直接呼叫父函式
父元件在模板用 @事件名="方法" → 接收事件並執行函式
這就是 Vue 官方推薦的「子呼叫父」方式,最安全、最解耦