VUE 非父子组件之间的传值

2023-06-06  本文已影响0人  小黄不头秃
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- 
        非父子组件之间的传值
        (1)单独的事件中心管理组件之间的通信
            - var eventHub = new Vue()
        (2)监听事件与销毁事件
            - eventHub.$on('add-todo',addTodo)
              eventHub.$off('add-todo')
        (3)触发事件
            - eventHub.$emit('add-todo',id)
     -->
    <div id="app">
        <div>父组件</div>
        <test-tom></test-tom>
        <test-jerry></test-jerry>
        <button @click="handel">销毁</button>
    </div>
    <script src="./vue/vue.js"></script>
    <script>
        // 提供事件中心
        var hub = new Vue();

        Vue.component(
            "test-tom",{
                data:function(){
                    return {
                        num:0
                    }
                },
                template:`
                <div>
                    <div>tom:{{num}}</div>
                    <div>
                    <button @click='handel'>点击</button>
                    </div>
                </div>
                `,
                methods:{
                    handel:function(){
                        // 触发兄弟组件的事件
                        hub.$emit('jerry-event',1);
                    }
                },
                mounted:function(){
                    // 监听事件
                    hub.$on('tom-event',(val)=>{
                        this.num+=val;
                    });
                }
            }
        );
        Vue.component(
            "test-jerry",{
                data:function(){
                    return {
                        num:0
                    }
                },
                template:`
                <div>
                    <div>jerry:{{num}}</div>
                    <div>
                    <button @click='handel'>点击</button>
                    </div>
                </div>`,
                methods:{
                    handel:function(){
                        // 触发兄弟组件的事件
                        hub.$emit('tom-event',1);
                    }
                },
                mounted:function(){
                    // 监听事件
                    hub.$on('jerry-event',(val)=>{
                        this.num+=val;
                    });
            }
        }
        );
        var vm = new Vue({
            el:"#app",
            data:{},
            methods:{
                handel:function(){
                    hub.$off('tom-event');
                    hub.$off('jerry-event');
                }
            }
        });
    </script>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读