Vue父子组件传值$parent , ref,$refs

时间:2019-08-11
本文章向大家介绍Vue父子组件传值$parent , ref,$refs,主要包括Vue父子组件传值$parent , ref,$refs使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

子组件

 1 <template>
 2     <div class="child">
 3         <slot name='meiyong'></slot>
 4         <p >我是子组件哟 {{num}} {{ttttt}} {{nike}}</p>
 5         <slot name="strong"></slot>
 6     </div>
 7 </template>
 8 <script>
 9 import Utils from '@/utils/utils'
10 export default {
11     props:['ttttt','nike'],
12     data(){
13         return {
14             num:" "
15         }
16     },
17     mounted(){
18         //传值给父组件
19         this.$parent.runTime= Utils.formatDate(new Date(), "YYYY-MM-DD hh:mm:ss");
20     }
21     
22 }
23 </script>
24 <style lang="scss" scoped>
25     .child{
26         height: 5rem;
27         width: 100%;
28         background-color: skyblue;
29         text-align: center;
30         position: relative;
31         p{
32             height: 30px;
33             width: 800px;
34             display: block;
35             position: absolute;
36             top: 0;
37             bottom: 0;
38             left: 0;
39             right: 0;
40             margin: auto;
41             // transform: translate(-50%,-50%)
42         } 
43         .parent{
44         color:greenyellow;
45         }
46         .strong{
47             position: absolute;
48             bottom: 0;
49             left: 50%;
50             transform: translateX(-50%);
51             color: darkmagenta;
52         }
53     }
54 </style>

父组件:

<template>
    <div >
    <!-- 父传子-->
        <tc :ttttt='mongodb' ref="ttttt" :nike='nike'>
            <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(){
        // num不是传的值 所以要ref才能传
        this.$refs.ttttt.num = '1949'
    },
    components:{
        tc:testChild
    }
}
</script>
<style lang="scss" scoped>
   
</style>

原文地址:https://www.cnblogs.com/it-Ren/p/11335040.html