WoJ
WoJ

Reputation: 29987

How to check in Vue3 if an element has children?

I would like to check (Vue3) if an element has children.

The documentation explains how to access DOM elements but I do not know how to check for content. Specifically, I do not know what type the variable is (container in the code below) and therefore how to check for its size/structure.

The general code I imagine should work is below, but it does not (this is just general code to sho the idea, I use .vue components so the code is compiled)

const app = Vue.createApp({
  setup() {
    let container = ref(null)
    if (container.value === null) {
      console.log("container is empty")
    } else {
      console.log("container has elements")
    }
    return {}
  }
}).mount("#app")
<div id="app">
  <div ref="container">
    <div></div>
  </div>
</div>

Upvotes: 0

Views: 4249

Answers (3)

IVO GELOV
IVO GELOV

Reputation: 14259

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>

Upvotes: 1

sungryeol
sungryeol

Reputation: 4005

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.

Upvotes: 2

Boussadjra Brahim
Boussadjra Brahim

Reputation: 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/[email protected]/dist/vue.global.prod.js"></script>

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

Upvotes: 1

Related Questions