美文网首页
4.组件之间数据传递

4.组件之间数据传递

作者: nora_wang | 来源:发表于2019-06-25 10:04 被阅读0次

组件之间包含嵌套关系时,需要通过数据传递,父组件与子组件相互通信。
1.父----> 子 (props)
父组件通过对属性进行动态绑定。

<template>
    <div>
        <p>我是父组件</p>
        <div class="parent">
            <!--子组件可通过props获取num的值-->
            <p :num="num">{{ num }}</p>
            <child />
        </div>
        <!--父级通过绑定自定义属性,向子级传递数据,子级通过props接收数据-->
        <!--父组件通过自定义事件,来接收子组件传递过来的数据-->
        <child :title="msg" @sendChild="sendChild" />
    </div>
</template>

子组件通过props来接受父组件传递的数据。

 export default {
        name: "child",
        data(){
            return{
                
            }
        },
        props:{
            title:{
                type:[Number,String],
                default:'暂无数据'
            }
        }

props也可以是数组 : props: ['title']

2.子向父传递数据 emit
子组件可以通过调用内建的 $emit方法,并传入事件名称来触发一个事件,向父级组件进行数据的传递。
子组件:

<button @click="setData" style="width: 60px;height: 40px;">确定</button>

通过触发函数setData来向父级传递当前msg的值

methods:{
            setData(){
                //$emit()向父级传递数据,包含两个参数,key,value
                this.$emit('sendChild',this.msg);
            }
        }

父级通过触发事件名为sendChild来进行接收

<child :title="msg" @sendChild="getChild" />

父级定义一个函数名为getChild,来接收,其函数的参数则为他所获取子组件中传递的值,并将所接收的值传给当前的childData

methods:{
            sendChild(data){
                this.childData = data;
            }
}

结论:父传子,父组件通过动态绑定属性的形式,子组件通过props进行接收。
子传父通过触发事件调用$emit的方式进行传递。

相关文章

网友评论

      本文标题:4.组件之间数据传递

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