vue 非父子通信

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <maweihua></maweihua>
        <kangchen></kangchen>
    </div>
    <script>
        let hanfei = new Vue();
        let maweihua = {
            template: `<div>
                        <h1>这是马伟华</h1>
                        <button @click="my_click">点我向康抻说话</button>
                        </div>`,
            methods: {
                my_click: function () {
                    console.log("")
                    // 向康抻说话
                    // 向中间调度器提交事件
                    hanfei.$emit("maweihua_say", "晚上等我一起吃饭~~~")
                }
            }
        };
        let kangchen = {
            template: `<div><h1>这是康抻</h1>{{say}}</div>`,
            data(){
              return {
                  say: ""
              }
            },
            mounted(){
                // 监听中间调度器中的方法
                let that = this;
                hanfei.$on("maweihua_say", function (data) {
                    console.log(data)
                    that.say = data
                })
            }
        };

        const app = new Vue({
            el: "#app",
            components: {
                maweihua: maweihua,
                kangchen: kangchen
            }
        })

    </script>
</body>
</html>

 

猜你喜欢

转载自www.cnblogs.com/bozhengheng/p/12070596.html