Vue父子組件傳值$parent , ref,$refs,props大總結


子組件:

<template>
    <div class="child">
        <slot name='meiyong'></slot>
        <p >我是子組件喲 {{num}} {{ttttt}} {{nike}} 這是我獨有的----->{{isChi}} </p>
        <slot name="strong"></slot>
    </div>
</template>
<script>
import Utils from '@/utils/utils'
export default {
    props:['ttttt','nike'],
    data(){
        return {
            num:" ",
            isChi:'★子組件獨有★'
        }
    },
    mounted(){
        //傳值給父組件
        this.$parent.runTime= Utils.formatDate(new Date(), "YYYY-MM-DD hh:mm:ss");
    }
    
}
</script>
<style lang="scss" scoped>
    .child{
        height: 5rem;
        width: 100%;
        background-color: skyblue;
        text-align: center;
        position: relative;
        p{
            height: 30px;
            width: 800px;
            display: block;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
            // transform: translate(-50%,-50%)
        } 
        .parent{
        color:greenyellow;
        }
        .strong{
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            color: darkmagenta;
        }
    }
</style>

 

父組件:

<template>
    <div >
    <!-- 父傳子-->
        <tc :ttttt='mongodb'  :nike='nike' ref="toChild">
            <template v-slot:meiyong >
                 <h1 class="parent">v-slot中的內容    沒用?呵呵</h1>
            </template>
            <template v-slot:strong>
                <h2 class="strong">你很強???{{runTime}} </h2>
            </template>
        </tc>
    </div>
</template>
<script>
import testChild from '@/views/testChild'
export default {
    data(){
        return {
            ttttt:'█我是父組件給child傳的值█',
            mongodb:'█我是MongoDB喲█',
            nike:'███ just do ███',
            runTime:'null'
        }
    },
    mounted(){
        let chi = this.$refs.toChild
        console.log('chi===>',chi.isChi);  
        this.$refs.toChild.isChi = '我試試能不能修改子組件的值'
       
        // num不是傳的值 所以要ref才能傳
        this.$refs.ttttt.num = '1949'
    },
    components:{
        tc:testChild
    }
}
</script>
<style lang="scss" scoped>
   
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM