前端-vue基础63-非父子组件传值

 

<!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>
    <div id="app">
        <div>父组件</div>
        <test-tom></test-tom>
        <test-jerry></test-jerry>
    </div>
    <script type="text/javascript" src="./js/vue.js"></script>
    <script>
        //提供事件中心
        var hub = new Vue();
        Vue.component('test-tom', {
            data: function() {
                return {
                    num: 0
                }
            },
            template: `<div>TOM:{{num}}
            <div><button  @click='handle'>点击</button></div></div>`,
            methods: {
                handle: 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>JERRY:{{num}}
            <div><button  @click='handle'>点击</button></div></div>`,
            methods: {
                handle: function() {
                    hub.$emit('tom-event', 2);
                }
            },
            mounted: function() {
                hub.$on('jerry-event', (val) => {
                    this.num += val;
                });
            }
        })
        var vm = new Vue({
            el: '#app',
            data: {
 
 
            },
 
        })
    </script>
</body>
 
</html>

 

posted @ 2022-07-23 22:30  前端导师歌谣  阅读(26)  评论(0)    收藏  举报