1. 程式人生 > >vue之非父子通訊

vue之非父子通訊

.非父子通訊:

思路: 找個中間儲存器,元件一把資訊放入其中,元件二去拿

程式碼如下:

        let hanfei = new Vue();  # 實列化個空的vue物件,作為中間儲存器來時間

        let maweihua = {

            template: `<div>

                        <h1>這是張三</h1>

                        <button

@click="my_click">點我向李四說話</button>

                        </div>`,

            methods: {

                

my_click: function () {

                    // 向李四說話,向中間排程器提交事件

                    hanfei.$emit("zhangsan_say", "晚上等我一起吃飯~~~")  # 向儲存器提交資訊用$emit

                }  # 括號內東西代表( 事件名字, 提交的資訊 )

            }

        };

        let kangchen = {

            template: `<div><h1>這是李四</h1>  {{say}}  </div>`,

            data(){

              return { say: "" }

                 },

            mounted(){   #  mounted這個鉤子函式在載入完成後還會一直監聽

                // 監聽中間排程器中的方法

                let that = this;

                hanfei.$on("zhangsan_say", function (data) {   # 從儲存器中取值用$on

                    that.say = data  # 只要中間儲存器內有對應事件的資料發生改變,就讓其反應到data

                })  # 接上, 內的say.

            }

        };

 

        const app = new Vue({

            el: "#app",

            components: {

                maweihua: maweihua,

                kangchen: kangchen

            }

        })