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

<body>
    <div id="root">
        <child content="Dell"></child>
        <child content="Lee"></child>
    </div>
    <script>
        Vue.prototype.bus = new Vue();//挂载一个bus属性

        Vue.component('child',{
            data: function(){
                return {
                    selfContent: this.content
                }
            },
            props: {
                content: String
            },
            template: "<div @click='handleClick'>{{selfContent}}</div>",
            methods: {
                handleClick: function(){
                    this.bus.$emit('change', this.selfContent)
                }
            },
            mounted: function() {
                var this_ = this;//这里this的作用域改变了
                this.bus.$on('change', function(msg) {
                    this_.selfContent = msg
                })

            }
        })
        var vm = new Vue({
            el: '#root',
            data: {

            }
        })
    </script>
</body>

猜你喜欢

转载自blog.csdn.net/twinkle_j/article/details/81097194
今日推荐