在vue的開發過程當中組件的通訊有一下幾種方式html
父傳子:propsvue
子傳父:emitvuex
vuex狀態管理函數
bus總線機制 this
var bus = new Vue()component
Vue.component("xiongda",{ data:function(){ return { xiongDaInput:"" } }, methods:{ sendToXiongEr:function(){ //給熊二發送消息 //觸發msgToXiongEr事件 bus.$emit("msgToXiongEr",this.xiongDaInput); this.xiongDaInput = ""; } }, template:` <div> <h1>我是熊大</h1> <input type="text" v-model="xiongDaInput"/> <button @click="sendToXiongEr">Click Me</button> </div> ` }) //熊二組件 Vue.component("xionger",{ data:function(){ return{ recvMsgIs:[] } }, template:` <div> <h1>我是熊二</h1> <p v-for="tmp in recvMsgIs">{{tmp}}</p> </div> `, mounted:function(){ // 給該組件綁定一個自定義事件和對應的處理函數 //調用bus中的on方法 //事件的觸發通常是接收數據而後處理 var that = this; bus.$on("msgToXiongEr",function(msg){ //alert("自定義的事件觸發,接收到的數據"+msg); that.recvMsgIs.push(msg); }) } }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>