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