美文网首页
非父子组件传值(bus)

非父子组件传值(bus)

作者: 葵自渡_ | 来源:发表于2019-05-23 16:31 被阅读0次
    1、我们需要做到这样一个效果,点击内容Sansa的组件,把值传给内容为Stark的组件,反之亦然
    <div id="app">
            <child name="Sansa"></child>
            <child name="Stark"></child>
        </div>
        <script>
            Vue.component('child',{
                template:'<div>{{name}}</div>',
                props:{
                    name:String
                }
            })
            var app = new Vue({
                el:'#app'           
            })
        </script>
    
    2、此时需要用到bus,给Vue上的prototype绑定bus属性,这个属性指向Vue实例。所以之后创建的vue实例都会有bus这样一个属性
    Vue.prototype.bus = new Vue()
    
    3、给div绑定click事件,点击时,alert。这就做到了点击谁弹出谁的效果。
    Vue.component('child',{
                template:'<div @click="handleClick">{{name}}</div>',
                props:{
                    name:String
                },
                methods:{
                        handleClick () {
                            alert(this.name)
                        }
                    }
            })
    
    4、此时我们需要把值传给兄弟组件,通过bus上$emit方法向外触发change事件,并携带了数据this.name
    methods:{
            handleClick () {
                this.bus.$emit('change',this.name)
            }
        }
    
    5、一个组件向外触发change事件,另一个组件要监听。这里用到mounted函数。info就是上面传来的值this.name
    mounted () {
            //这里要注意this作用域的改变
            var _this = this            
            this.bus.$on('change',function(info){
            _this.name = info
        })
    }
    
    6、此时效果都实现了,可是还有个问题,name是外部传来的值,子组件不能随意修改,因为单向数据流。此时只要定义个data,重新定义一个变量,把name赋值给它。
    <script>
            Vue.prototype.bus = new Vue()
    
            Vue.component('child',{
                template:'<div @click="handleClick">{{herName}}</div>',
                props:{
                    name:String
                },
                data () {
                    return {
                        //这样就可以修改了
                        herName:this.name
                    }
                },
                methods:{
                    handleClick () {
                        this.bus.$emit('change',this.herName)
                    }
                },
                mounted () {
                    //这里要注意this作用域的改变
                    var _this = this            
                    this.bus.$on('change',function(info){
                        _this.herName = info
                    })
                }
            })
            var app = new Vue({
                el:'#app'           
            })
        </script>
    

    相关文章

      网友评论

          本文标题:非父子组件传值(bus)

          本文链接:https://www.haomeiwen.com/subject/fnqbzqtx.html