非父子组件间的传值(4-5)

非父子组件间的传值

实现我点击上面那个,下面的就跟着变,点击下面那个上面那个就跟着变。

Vue.prototype.bus = new Vue()  挂载一个bus
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src='./vue.js'></script>
</head>
<body>
    <div id="root">
       <child content="Dell"></child>
       <child content="Lee"></child>
    </div>    
    <script>

        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: function() {
     
     
                    this.bus.$emit('change', this.selfContent)
                }
            },
            mounted: function() {
     
     
                var this_ = this
                <!--绑定bus里的监听事件$on-->
                this.bus.$on('change', function(msg) {
     
     
                    this_.selfContent = msg
                })
            }
        })

        var vm = new Vue({
     
     
            el: '#root'
        })
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_45647118/article/details/113967092