1-10 emit

    自定义事件

            我们知道,父组件使用prop传递数据给子组件,但子组件怎么跟父组件通信呢?这个时候Vue的自定义事件系统就派得上用场。

            这是父组件

<template>
    <div>
        父组件
        <Child @sendMsg="getMsg"/>
        {{info}}
    </div>
</template>
<script>
import Child from "./child"
export default {
    name:"parent",
    data(){
        return{
            info:''//初始化
        }
    },
    components:{
        Child
    },
    //在父组件中 定义一个方法,用来接收子组件所通过事件传来的值
    methods:{
        getMsg(data){
            //参数data就是子组件通过事件出来的数据
           this.info=data;
        }
    }
}
</script>
<style scoped>

</style>    

                这是子组件

<template>
    <div>
        子组件
        <button @click="sendMsg">传递</button>
    </div>
</template>
<script>
export default {
    name: "child",
    data() {
        return {
            msg: '我是子组件数据'
        }
    },
    methods: {
        sendMsg(event) {
            //两个参数:参数1:key 参数2:数据
            //$emit()——把事件沿着作用域链向上派送。(触发事件)
            this.$emit("sendMsg", this.msg)
            //触发一个叫做sendMsg的事件,同时把第二个参数数据传递给事件对应的处理函数
        }
    }
}
</script>
<style scoped>

</style>


    

猜你喜欢

转载自blog.csdn.net/weixin_37404604/article/details/80293364