[Vuejs]-V-if based on result of DOM updating

1👍

I did it using the watchers in Vue, I hope it will help you !

<template>
  <button @click="addDiv">Click to add div</button>
  <div
    v-for="el in elements"
    :key="el.id"
  >
    <span ref="items">{{ el.text }}</span>
    <button v-if="el.showButton">Click me</button>
  </div>
</template>   

and the script, I’ve updated the typing part:

<script setup lang="ts">
  //imports
  import { ref, watch } from 'vue';

  const elements = ref<Array<any>>([]);
  const items = ref<Array<HTMLElement>>([]);

  const addDiv = function () {
    elements.value.push({ text: 'Test', id: Date.now(), showButton: false });
  };

  watch(items.value, (newItems) => {
    console.log('items changed');
    let cpt = 0;

    // you can do it with a for loop too
    newItems.forEach((item) => {
      if (item.scrollHeight > item.offsetHeight) {
        console.log('overflow -> show button');
        elements.value[cpt].showButton = true;
      }
      cpt++;
    });
  });
</script>

Leave a comment