this.$refs 父组件向子组件传值

2024-04-02  本文已影响0人  缘之空_bb11
<template>
 <Child ref="child"></Child>
</template>
 
<script>
    export default {
        name: "Parent",
        data () {
            return {
            }
        },
        mounted() {
            this.$nextTick(() => {
                this.$refs.child.childflag = true;
            }
        }
        methods: {
            this.$nextTick(() => {
                // 父组件调用子组件方法
                this.$refs.child.childMethod(); 
                // 父组件赋值子组件的数据
                this.$refs.child.childflag = false;    
            }
            
        }
    }
</script>

注意:

可能会出现this.$refs 获取不到值的问题,原因有:

1、使用this.$refs如果要在mouend()中使用,必须要在this.$nextTick(()=>{ }) 这里面实现,要不然找不到ref,原因是mouned()之前,BOM节点还没有完全挂载上,于是找不到定义的ref。

2、可以直接在updata()的生命周期函数中使用,不用写this.$nextTick(()=>{ }) 。

3、在methods:{ } 方法中使用,也需要使用this.$nextTick(()=>{ } ) 等到页面完全渲染完毕之后在调用即可。

4、组件在v-if为false的父节点下,导致这个子组件未渲染,也是导致获取不到的因素。

// 父组件
export default {
  props: {
    refs: Object
  },
  mounted() {
    // 使用refs
    console.log(this.refs);
  }
}

然后,在父组件的模板中,将$refs绑定到子组件的prop上:

<!-- 父组件模板 -->
<child-component :refs="this.$refs" />

子组件不需要做任何特殊的处理,只需要像常规prop一样接收它。
请注意,直接传递this.\$refs可能不是最佳实践,因为\$refs通常是用来注册DOM引用的,而不是用来传递数据的。如果你需要传递特定的数据或方法到子组件,请考虑使用事件或者Vuex来实现

上一篇 下一篇

猜你喜欢

热点阅读