2019-08-21 Vue多層組件通信

先看一個demo

<body>

    <div id="app">
        <my_parent :parentimg="img" :parenttitle="title"></my_parent>
    </div>

    <template id="myimg">
        <img :src="imgsrc">
    </template>

    <template id="mytitle">
        <h2>{{childtitle}}</h2>
    </template>

    <template id="parent">
        <div>
            <child1 :imgsrc="parentimg"></child1>
            <child2 :childtitle="parenttitle"></child2>
        </div>
    </template>
</body>

<script src="../js/vue.js"></script>
<script>
    //創(chuàng)建子組件實例
    let profile1 = Vue.extend({
        template:"#myimg",
        props: ["imgsrc"]
    });
    let profile2 = Vue.extend({
        template:"#mytitle",
        props:["childtitle"]
    });

    //注冊父組件
    Vue.component("my_parent" , {
        props: ["parentimg" , "parenttitle"],
        components: {
            "child1":profile1 ,
            "child2":profile2
        },
        template:"#parent",
    });

    new Vue({
        el:"#app",
        data:{
            title:"我是不是很美!",
            img:"../img/img_02.jpg"
        }
    })
</script>

組件之間主要通過props進行值傳遞
上面demo中data中的img和title首先將值傳遞給父組件props的parentimg 和parenttitle,parentimg和parenttitle將值傳給imgsrc和childtitle,imgsrc和childtitle將值傳給子組件的src和<h2>{{}}</h2>

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容