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

<body>
    <div id="app">
        <child content="Dean"></child>
        <child content="Wade"></child>
    </div>

    <script>
        Vue.component('child', {
    
    
            props: {
    
    
                content: String
            },
            template: '<div>{
    
    {content}}</div>'
        })
        var vm = new Vue({
    
    
            el: '#app',
            data: {
    
    },
            methods: {
    
    
                handleClick() {
    
    
                    console.log('root component clicked!')
                }
            }
        });
    </script>
</body>

在这里插入图片描述
我们想实现,通过点击上面的Dean,把下面的Wade改成Dean,点击下面的Wade,上面的Dean会变成Wade。这样的需求涉及到非父子组件间传值

<body>
    <div id="app">
        <child content="Dean"></child>
        <child content="Wade"></child>
    </div>

    <script>
        // 挂载到Vue的原型上
        Vue.prototype.bus = new Vue()
        Vue.component('child', {
    
    
            data: function(){
    
    
                return {
    
    
                    selfContent: this.content
                }
            },
            props: {
    
    
                content: String
            },
            template: '<div @click="handleClick">{
    
    {selfContent}}</div>',
            methods: {
    
    
                handleClick() {
    
    
                    // 点击把自己的值传递给另一个组件
                    this.bus.$emit('change', this.content)
                }
            },
            mounted: function() {
    
    
                var this_ = this
                console.log('this_:', this_)
                this.bus.$on('change', function(msg){
    
    
                    this_.selfContent = msg                    
                })
            }
        })
        var vm = new Vue({
    
    
            el: '#app',
            data: {
    
    }
        });
    </script>
</body>

在这里插入图片描述
在这里插入图片描述
注意这里的this的含义:指向每个组件自身
在这里插入图片描述
在这里插入图片描述
还有就是为什么要保存this_ = this
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/dyw3390199/article/details/112425077
今日推荐