Vue的非父子组件之间的传值 bus(总线/观察者模式)

比如有一个bus对象,这个对象上有两个方法,一个是on(监听,也就是订阅),一个是emit(触发,也就是发布),我们通过on方法去监听某个事件,再用emit去触发这个事件,同时调用on中的回调函数,这样就完成了一次事件触发;

总线bus方式进行传递, hello组件的text传递给world组件

 <hello content=“one”></hello>
 <world content=“two”></world>

  script:

   在生成vue实例前,给Vue的原型上添加一个bus属性,这个属性是vue的实例,

 Vue.prototype.bus = new Vue();

  

  //组件hello
        Vue.component('hello', {
            data() {
                return {
                    text:'hello'
                }
            },
            template: '<div @click="handlerClick">{{text}}</div>',
            methods: {
                handlerClick: function(){
                    this.bus.$emit('sharetext', this.text)//触发事件sharetext
                }
            }
        })

  

  //组件world
        Vue.component('world', {
            data() {
                return {
                    text: ''
                }
            },
            template: '<div>{{text}} world</div>',
            mounted: function(){
                //let _this = this;因为this的指向发生了变化,不用箭头函数的话就要先把this保存起来
                this.bus.$on('sharetext', text => {//通过$on监听事件sharetext
                    this.text = text 
                })
            }
        })

  

        //根实例
        var vm = new Vue({
            el: '#app',
    })

  

猜你喜欢

转载自www.cnblogs.com/yubaibai/p/10701608.html