Vue.js 基础学习之组件通信

今天我们学习组件的通信,解除我上一次的疑问,如何将组件的数据传出去,又如何拿进来

父子通信

第一个例子是将new的vue中的数据传递给组件

<div id="app">
        <userlink :username="username"></userlink>
    </div>
<script>
        Vue.component('userlink',{
            template: '<a href=" \'user\' + username">{{ username }}</a>',
            props : ['username'],
        });
       var app =  new Vue({
            el: '#app',
            data : {
                username : 'Tom',
            },
        });
    </script>

通过组件的props对应的一个数组绑定userlink 的属性 username,然后再通过v-bind绑定到data的username,这样通过改变app的username就可以改变组件中的username。

嵌套组件的通信

<div id="app">
<Dog></Dog>
</div>
<script>
    Vue.component('Dog',{
        template: `<div>
        <show @show_Dog="on_show_Dog"></show>
        <div v-if="show">this is a dog</div>
        </div>`,
        data : function(){
            return {show : false};
        },
        methods : {
            on_show_Dog : function(){
                this.show = true;
            }
        }
    });
    Vue.component('show',{
        template : '<button @click="on_click">这是啥?</button>',
        methods : {
            on_click : function(){
                this.$emit('show_Dog',{a: 1 , b: 2});
            }
        },
    });
    new Vue({
        el : '#app',
    })
</script>

上面代码通过点击子组件中的button来操控父组件,中div的显示与否。详细过程为:

为子组件中的button绑定一个点击事件,在点击事件触发时,通过this.$emit()调用在父组件的template中给子组件的标签中绑定的这个事件,当此事件触发时,将父组件中的data数据show赋值为true,这样在v-if判断下就显示出来了。

平行通信

<div id="app">
        <Send></Send>
        <receive></receive>
    </div>

 

<script>
    var Event = new Vue();
    Vue.component('Send',{
        template : `<div>
            发送:<input @keyup='on_keyup' type="text" v-model='news' />{{ news }}
        </div>`,
        data : function(){
            return {
                news : '',
            };
        },
        methods : {
            on_keyup : function(){
                Event.$emit('s_r',this.news);
            }
        }
    });

    Vue.component('receive',{
        template : `<div>
        接收:{{ news }}
        </div>`,
        data : function(){
            return {
                news : '',
            };
        },
        mounted: function(){
            var that = this;
            Event.$on('s_r',function(data){
                that.news=data;
            });
        }
        });

    new Vue({
        el : '#app',
    })
</script>

上面这段代码的作用是将组件send中的数据news传递给receive并赋值给receive的news然后显示出来。这里重点是用到了外部的一个事件的调度器Event,用Event.$on()绑定事件,连个参数,第一个是绑定事件的名称,第二个是绑定事件触发的函数,在send中用Event.$emit()触发事件,两个参数,第一个是事件名称,第二个是传递的参数,当input中的keyup事件触发时,Event.$emit()触发receive中通过Event.$on()绑定的事件,从而接收到参数,再在receive中显示出来。

posted @ 2017-09-03 23:08  hz海内存知己  阅读(168)  评论(0编辑  收藏  举报