前端mvvm框架vue.js(3)——父子組件通信

vue.js父子組件通信:1,父組件向子組件傳遞數(shù)據,通過props,注意數(shù)據綁定是單向的(借鑒了react);2,子組件向父組件傳遞數(shù)據,通過在子組件自定義事件,使用this.$dispatch()觸發(fā)自定義事件,事件冒泡到父組件,同時在父組件內通過events或者methods,聲明回調函數(shù),同時通過this.$dispatch()傳遞的參數(shù)將傳給父組件在events和methods中的會調函數(shù),此時可以在回調函數(shù)中操作參數(shù)。

1,父組件向子組件傳遞數(shù)據

<div id="prop">
    <input v-model="parentMSG">
    <child :my-message="parentMSG"></child>
</div>

  //props傳遞父組件數(shù)據,默認為單向綁定,注意:字面量語法傳遞的是字符串,如需要傳遞實際數(shù)值,需使用動態(tài)語法v-bind:或縮寫模式:(也即可以看成是表達式的方式),支持修飾符.sync和.once綁定修飾符,綁定動態(tài)props,注意使用駝峰形式的props時,需要轉換為短橫杠的形式
    Vue.component("child",{
        props:{
            myMessage:{
                type:String,
                required:true,
                coerce:function(str){
                    return str.slice(2);
                }
            }
        },
        template:"<span>{{myMessage}}</span>"
    });
    var propVM=new Vue({
        el:"#prop",
        data:{
            parentMSG:""
        }
    })
//此例中我們通過v-model將input中的數(shù)據綁定到父組件模板中,此時input和父組件數(shù)據是雙向綁定,input數(shù)據傳遞給在子組件中定義的props,再將props傳遞給子組件中的span子元素,實時更新

2,子組件向父組件傳遞數(shù)據

<template id="child-template">
    <input v-model="msg">
    <button v-on:click="notify" >觸發(fā)自定義事件</button>
    {{childmsg}}
</template>
<div id="events-example">
    <p>Message:{{messages|json}}</p>
//通過methods方法時,注意需要在父組件模板中的子組件上綁定事件
    <child v-on:child-msg="handleIt"></child>
//通過events方法時,只需在父組件的選項對象中events,寫入child-msg方法
//我們還可以在父組件事件監(jiān)聽回調中,通過props將數(shù)據傳回個子組件
    <child :childmsg="messages"></child>
</div>

    Vue.component("child",{
        template:"#child-template",
        data:function(){
            return {msg:"hello"};
        },
        methods:{
         //這里是button按鈕點擊后的事件處理函數(shù)
            notify:function(){
                if(this.msg.trim()){
        //在這里我們綁定了一個子定義的事件child-msg,同時傳入一個參數(shù),此參數(shù)可以傳遞給父組件的事件回掉函數(shù)
                    this.$dispatch("child-msg",this.msg);
                    this.msg="";
                }
            }
        }
    });
    var eventParent=new Vue({
        el:"#events-example",
        data:{
            messages:[]
        },
        props:{parentprop:""},
//我們可以在這里注冊子組件自定義事件監(jiān)聽回調
        methods:{
            // handleIt:function(msg){
            //    console.log("子組件回調函數(shù)");
            //    this.messages.push(msg);
            // }
        },
//同時我們也可以在events中注冊子組件自定義事件監(jiān)聽回調
        events:{
            "child-msg":function(msg){
               this.messages.push(msg);
               this.parentprop=msg;
               console.log("子組件事件被觸發(fā)");
            }
        }
    })
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容