vue父组件通过ref获取子组件data数据出现undefined(问题篇)

本文介绍了在Vue中如何从父组件获取子组件的数据,通过`this.$nextTick`和`setTimeout`实现数据延迟加载,确保父组件能够正确获取到子组件更新后的数据。示例代码详细展示了这两种方法的用法。
摘要由CSDN通过智能技术生成

解决办法:

1、使用this.$nextTick

<template>
  <!-- 父组件 -->
  <div class="box" style="margin:20px">
    <child ref="childData"></child>
    <button @click="handelAZiZuJian">点击</button>
  </div>
</template>
<script>
import child from "./child.vue";
export default {
  components: {
    child,
  },
  data() {
    return {
    };
  },
  created() {
    //使用this.$nextTick()
    this.$nextTick(() => {
      this.handelStrData();
    });
  },
  methods: {
    handelStrData() {
      console.log(this.$refs["childData"].objData);
    },
    handelAZiZuJian() {
      this.$refs.childData.handelAlert();
    },
  },
};
</script>

2、使用setTimeout()

<template>
  <!-- 父组件 -->
  <div class="box" style="margin:20px">
    <child ref="childData"></child>
    <button @click="handelAZiZuJian">点击</button>
  </div>
</template>
<script>
import child from "./child.vue";
export default {
  components: {
    child,
  },
  data() {
    return {
    };
  },
  created() {
     this.handelStrData();
  },
  methods: {
    handelStrData() {
     //使用setTimeout()延时加载
     setTimeout(() => {
        console.log(this.$refs["childData"].objData);
     }, 10);
    },
    handelAZiZuJian() {
      this.$refs.childData.handelAlert();
    },
  },
};
</script>

这样就可以获取子组件的data中的数据。代码可复制查看。

Vue2组件组件可以通过`$parent`属性来访问组件的实例,但是不建议这样做,因为这样会使得组件之间的耦合度过高,不利于组件的复用和维护。更好的做法是通过`props`和`$emit`来实现组件之间的通信。 如果需要组件组件调用组件数据,可以通过在组件定义一个`ref`,然后在组件组件通过`$refs`来访问组件的实例,从而获取组件数据。具体实现步骤如下: 1.在组件定义一个`ref`,例如`childRef`。 ```vue <template> <div> <button @click="childFun">组件按钮</button> </div> </template> <script> export default { name: "child", data() { return {}; }, methods: { childFun() { this.$emit("child-event", "组件要传达到组件数据"); }, }, }; </script> <style lang='less' scoped> </style> ``` 2.在组件监听组件的自定义事件,并将组件数据通过`$emit`方法传递给组件。 ```vue <template> <div> <child ref="childRef" @child-event="handleChildEvent"></child> </div> </template> <script> import Child from "./Child.vue"; export default { name: "parent", components: { Child, }, methods: { handleChildEvent(data) { console.log(data); // 组件要传达到组件数据 console.log(this.$refs.childRef); // 组件实例 }, }, }; </script> <style lang='less' scoped> </style> ``` 注意:在组件通过`$refs`访问组件的实例时,需要等到组件渲染完成后才能访问,否则会返回`undefined`。可以在组件的`mounted`钩函数访问组件的实例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值