无法更改后代组件代码情况下,vue2代码this.$refs.detailChid.$children[0].$children[0].xxx变更成vue3后代码如何实现?

VUE2升级到vue3中,原vue2中的通过this.$refs.detailChid.$children[0].$children[0].xxx去获取后代的组件的数据,$refs.detailChid是从依赖中进行全局注册的组件,其内部组件无法更改,无法通过Provide 和 Inject,也无法通过vuex等方式去获取数据, 现在有什么办法拿到后代组件的数据吗?后代组件仍然是vue2写法暴露出来的,没有使用setup,也没有使用一些vue3不兼容的语法

讨论数量: 5
<template>
  <div>
    <ChildComponent ref="detailChild" />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  setup() {
    const detailChild = ref(null);

    onMounted(() => {
      // 访问子组件的方法或数据
      if (detailChild.value) {
        // 假设子组件有一个方法叫 doSomething()
        detailChild.value.doSomething();
      }
    });

    return {
      detailChild
    };
  }
};
</script>

然后直接在子组件里定义doSomething输出子组件的对应数据就好了,而且本身不能使用 Provide 和 Inject就不合理,属于是组件定义上就有问题了。最节省的方法就直接定义个事件总线。

2个月前 评论
yinqiang_001 (楼主) 2个月前
Egoist-Berserker (作者) 2个月前
yinqiang_001 (楼主) 2个月前
yinqiang_001 (楼主) 1个月前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!