解决办法:

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中的数据。代码可复制查看。

Logo

前往低代码交流专区

更多推荐