[Vuejs]-How to check in Vue3 if an element has children?

1👍

You could use container.value.children in onMounted hook to check if the referenced element has children because in this hook the DOM is rendered.

const app = Vue.createApp({
  setup() {
    let container = Vue.ref(null)
    Vue.onMounted(() => {


      if (container.value && container.value.children.length) {

        console.log("container has elements")
        console.log(container.value.children)
        
      } else {
        console.log("container is empty")
      }
    })
    return {
      container
    }
  }
}).mount("#app")
<script src="https://unpkg.com/vue@3.0.0-rc.11/dist/vue.global.prod.js"></script>

<div id="app">
  <div ref="container">
    <div>test</div>
  </div>
</div>

2👍

Check the context part of Vue3 setup API

<template>
  <div class="container">
    <slot></slot>
    <span v-show="hasChildren">hasChildren</span>
  </div>
</template>

<script>
export default {
  // ...
  setup(props, { slots }) {
    let hasChildren = false;
    if (slots.default) {
      hasChildren = slots.default().length >= 1;
    }
    return { hasChildren };
  }
}
</script>

Here’s the running example:

https://codepen.io/rabelais88/pen/xxdBmRP

It’s an abstraction with component, so it’s possible to re-use later.

1👍

The variable container in your code is of type HTMLElement – so you can check whether its childElementCount property is bigger than zero.

const app = Vue.createApp({
  mounted()
  {
    console.log(this.$refs.container.childElementCount);
    console.log(this.$refs.emptyContainer.childElementCount);
  }
}).mount("#app")
<script src="https://unpkg.com/vue@3"></script>

<div id="app">
  <div ref="container">
    <div></div>
  </div>
  <div ref="emptyContainer"></div>
</div>

Leave a comment