vue——14-组件之间的通信(单层和多层)

版权声明:转发博客 请注明出处 否则必究 https://blog.csdn.net/lucky541788/article/details/82745155

单层

<div id="enjoy">
    <my-div message="hello girl" imgSrc="../images/fashion-001.jpg"></my-div>
    <my-div message="hello boy" imgSrc="../images/fashion-002.jpg"></my-div>
</div>


<template id="my_div">
    <div>
        <h1>{{message}}</h1>
        <!--注意:vue中不支持大写的驼峰式命名-->
        <img :src="imgsrc" alt="" width="300">
    </div>
</template>
        {
            //1.创建组件
            Vue.component('my-div', {
                template: '#my_div',
                props:['message','imgsrc']
            });
            new Vue({
                el: '#enjoy',
                data: {
                    msg: 'hello!'
                }
            })
        }

这里写图片描述

多层

<!--数据必须动态绑定:v-bind 或 : -->
<div id="enjoy">
    <my-father :imgtitle="title" :imgsrc="img"></my-father>
</div>

<template id="my_img">
    <img :src="imgsrc" width="200" alt="">
</template>

<template id="my_title">
    <h2>{{title}}</h2>
</template>

<template id="father">
    <div>
        <child1 :imgsrc="imgsrc"></child1>
        <child2 :title="imgtitle"></child2>
    </div>
</template>
        {
            //1.子组件实例
            let Child1=Vue.extend({
                template:'#my_img',
                props:['imgsrc']
            });

            let Child2=Vue.extend({
                template:'#my_title',
                props:['title']
            });

            //2.注册父组件
            Vue.component('my-father',{
                template:'#father',
                props:['imgtitle','imgsrc'],
                components:{
                    child1:Child1,
                    child2:Child2
                }
            });


            new Vue({
                el:'#enjoy',
                data:{
                    title:'my name is john!',
                    img:'../images/fashion-001.jpg'
                }
            })
        }

这里写图片描述

猜你喜欢

转载自blog.csdn.net/lucky541788/article/details/82745155