vue中央事件总线

111 阅读1分钟

中央事件总线

<body>
    <div id="app"></div>
    <script src="./js/vue.js"></script>
    <script>
        var bus = new Vue();
        Vue.component('brother1',{
            data(){
                return{
                    msg:''
                }
            },
            template:`
                <div>
                    <h3>我是brother1组件</h3>
                    <input v-model='msg' v-on:input='clickHandler(msg)'>
                    <brother2></brother2>
                </div>
            `,
            methods:{
                clickHandler:function(val){
                    bus.$emit('clickHandler',val)
                }
            }
        });
        Vue.component('brother2',{
            data(){
                return{
                    message:''
                }
            },
            template:`
                <div>
                    <h3>我是brother2组件</h3>
                    <h3>我是brother1传来的数据:{{message}}</h3>
                </div>
            `,
            mounted(){
                bus.$on('clickHandler',(val)=>{
                    this.message = val;
                })
    
            }
        })
        var App ={
            template:`
                <brother1 />
                
            `
        }
        new Vue({
            el:'#app',
            components:{
                App
            },
            template:`<App />`
        });
    </script>
</body>