Vue中利用$emit实现子组件向父组件通信


Vue中利用$emit实现子组件向父组件通信

父组件

<template>
    <div>
        <p>我是父组件</p>
        <child :isShow="show" @hidechild="hidechild"></child>
        <button @click="show=true">显示子组件</button>
    </div>
</template>

<script>
    import child from "./child"
    export default {
        date(){
            return{
                show:false
            }
        },
        components:{
            child
        },
        methods:{
            hidechild:function () {
                this.show=false
            }
        }
    }
</script>

子组件

<template>
    <div>
        <h2 v-show="isShow">我是子组件</h2>
        <button @click="hideMyself()">隐藏子组件</button>
    </div>
</template>

<script>
    export default {
        name:"child",
        props:{
            isShow:Boolean
        },
        methods:{
            hideMyself:function () {

                this.$emit('hidechild');

                //通过调用父组件的方法改变props中参数的内容
                //$emit(eventname,args); 可以携带参数
            }
        }
    }
</script>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM