[Vuejs]-How to get the reference of recursive components in Vue3?

0👍

To get the nested refs you will need to traverse the tree yourself.

There is no ready to use solution for it.

Here is very basic example of going through refs including all nested children.

const { createApp, ref } = Vue;

const CompB = {
  props: ['id'],
  setup(props) {
    const name = "CompB"
    return { name } 
  },
  template: '<div class="b">CompB, id:<b>{{id}}</b></div>'
}

const CompA = {
  components: { CompB },
  props: ['id'],
  setup(props) {
    const name = "CompA"
    const child = ref(null)   
    return { name, child } 
  },
  template: '<div class="a">CompA, id:<b>{{id}}</b><CompB ref="child" :id="`${id}.1`" /></div>'
}

const App = { 
  components: { CompA },
  setup(props) {
    const refs = ref([])
    const showRefs = (ref) => {
       if (!ref) {
          for(var i = 0; i < refs.value.length; i++) {
            console.log(`Name: ${refs.value[i].name}, id: ${refs.value[i].id}`);
            if (refs.value[i].child) showRefs(refs.value[i].child)
          }
       } else {
          console.log(`Name: ${ref.name}, id: ${ref.id}`);
       }
    }
    return { refs, showRefs } 
  }
}
const app = createApp(App)
app.mount('#app')
#app { line-height: 2; }
[v-cloak] { display: none; }
.a { 
  background-color: lightblue;
  margin: 4px;
  padding: 4px;
 }
.b { 
  background-color: lightyellow;
  margin: 4px;
  padding: 4px;
}
<div id="app" v-cloak>
<button @click="showRefs()">Show refs</button><br/>
<comp-a v-for="n in 3" :id="n" ref="refs"></comp-a>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

Leave a comment