vue2.0中通過$emit事件在子組件中自定義事件,通過操作子組件中的事件,向父組件傳遞參數;
首先寫一個叫做parentComp.vue的父組件:
<template> <div> <childComp01 :fromParentToChild="fromParentToChild" :isShow="show" @showParentComp="eventFromChild"></childComp01> <childComp02 @eventFromChild02="eventFromChild02" :fromParentToChild="fromParentToChild" :isShow="!show"></childComp02> </div> </template> <script> import childComp01 from './childComp.vue' import childComp02 from './childComp02.vue' export default{ data(){ return{ show:false,//是否展示子組件內容 fromParentToChild:"" } }, components:{childComp01,childComp02}, methods:{ showChild(){ this.show = true }, eventFromChild(dataIf){ console.log(dataIf.show) this.show=dataIf.show this.fromParentToChild = dataIf.mes }, eventFromChild02(dataIf){ console.log(dataIf.show) this.show=dataIf.show this.fromParentToChild = dataIf.mes } } } </script>
然后定義子組件childComp01和childComp02
<template> <div v-if="isShow"> <div>子組件內容01:</div> {{fromParentToChild}} <div> <button @click="showParentComp">點擊顯示子組件02內容</button> </div> </div> </template> <script> export default{ props:['fromParentToChild','isShow'], data(){ console.log(this.fromParentToChild) return{ dataIf:{ mes:"來自子組件01的內容", show:false } } }, methods:{ showParentComp(){ this.$emit("showParentComp",this.dataIf) } } } </script>
childComp02.vue
<template> <div class="childComp-02" v-if="isShow"> {{fromParentToChild}} <div><button @click="toParentComp">這是子組件02</button></div> </div> </template> <script> export default{ props:['isShow','fromParentToChild'], data(){ return{ dataIf:{ show:true, mes:"從子組件02傳過來的信息" } } }, methods:{ toParentComp(){ this.$emit("eventFromChild02",this.dataIf) } } } </script>