vue非父子组件间的传值 Bus/总线机制/发布订阅模式/观察者模式

版权声明: https://blog.csdn.net/xyphf/article/details/83658458

Bus/总线机制/发布订阅模式/观察者模式

我们需要将一个组件的子组件的数据传递给另一个组件的子组件

① 将Vue的实例赋值给Vue.prototype.bus,这样只要我们之后调用new Vue()或者创建组件的时候,每一个组件上都会有Bus这个属性,因为每一个组件或者Vue这个实例都是通过Vue这个类来创建的,而我们在Vue的类上挂了一个Bus的属性,而且挂在Vue类的prototype上面,所有每一个通过Vue创建的,也就是Vue的实例上都会有Bus这个属性,它都指向同一个Vue的实例。

②在子组件里面绑定一个点击事件,如 @click="handleClick", 

③在此提交一个自定义事件 如: this.bus.$emit('change',this.selfContent)

④在父组件中使用$on监听bus上触发出来事件

var this_ = this;  // this作用域发生了变化,所以在这里做一次保存

this.bus.$on('change',function(msg){
          this_.selfContent = msg;
})

⑤改变父组件接收过来的数据,要做一次备份,才方便修改,因为vue里面是单向数据流,子组件不能改变父组件,如下:

            data: function(){
                return {
                    selfContent: this.content
                }
            },

<body>
    <div id="app">
        <child content="hello"></child>
        <child content="world"></child>
    </div>

    <script>
        Vue.prototype.bus = new Vue()

        Vue.component('child', {
            props: ['content'],
            data: function(){
                return {
                    selfContent: this.content
                }
            },
            template: '<div @click="handleClick">{{selfContent}}</div>',
            methods:{
                handleClick: function(){
                    this.bus.$emit('change',this.selfContent)
                }
            },
            mounted: function(){
                var this_ = this;
                this.bus.$on('change',function(msg){
                    this_.selfContent = msg;
                })
            }
        })

        var vm = new Vue({
            el: "#app"
        })
    </script>
</body>

猜你喜欢

转载自blog.csdn.net/xyphf/article/details/83658458