在Vue項目中,經常使用$emit(),從子組件向父組件中發送消息,或者調用父組件中的方法。
但是,如果組件的嵌套層數比較多,使用$emit()就不是特別的方便的。
情況實例:組件A中使用了組件B,組件B中又使用了組件C。這時,想在組件C中向組件A發送消息。
// 組件A
<template>
<div>
<Child v-on:feedSunFn="feedSunFn"></Child>
</div>
</template>
<script>
import Child from "./Child";
export default {
name: 'HelloWorld',
data () {
return {
}
},
components:{
Child
},
methods:{
feedSunFn(val){
alert(val)
}
}
}
</script>
// 組件B
<template>
<div>
<Sun v-on="$listeners"></Sun>
</div>
</template>
<script>
import Sun from "./Sun";
export default {
name:"Child",
components:{
Sun
}
}
</script>
// 組件C
<template>
<div>
<button @click="clickBtn">這是孫子組件裏的一個按鈕</button>
</div>
</template>
<script>
export default {
name:"Sun",
methods:{
clickBtn(){
this.$emit("feedSunFn","來自孫子組件的消息")
}
}
}
</script>