非父子组件间传值(Bus/总线/发布订阅模式/观察者模式)

使用总线机制(bus)实现非父子组件间传值 

 在两个child组件间传值,实现点击一个child组件,另一个组件变成与此相同的值

<div id="root">
    <child content="the first value"></child>
    <child content="the second value"></child>
</div>
<script>
    Vue.prototype.bus=new Vue()
    Vue.component('child',{//定义一个全局组件
        props:{
            content: String
        },
        data: function(){
            return{
                selfContent:this.content
            }
        },
        template: '<div @click="handleClick">{
   
   {selfContent}}</div>',
        methods:{
            handleClick: function () {
                //alert(this.selfContent)
                this.bus.$emit('change',this.selfContent)
            }
        },
​​​​​​​       //在钩子函数中监听msg事件
        mounted:function (msg) {
            var this_=this;
            this.bus.$on('change',function (msg) {
                this_.selfContent=msg
            })
        }
    })
    var vm=new Vue({
        el: "#root"
    })
</script>

(待补充)

猜你喜欢

转载自blog.csdn.net/willard_cui/article/details/82468337
今日推荐