[Vuejs]-Best approach for adding animation to large text blocks in Vue

0đź‘Ť

Considering this is static text and not true data binding, I think this is a case where you use methods similar to how you would handle this without Vue, just with a couple Vue helpers to make it nicer.

The method that seems the most straightforward to me is to wrap the expandable paragraphs and get a reference to the wrapper element. When the component loads, loop through the element’s children and hide all but the first one.

We still use the counter, but we use it as an index into the wrapper’s children to determine which to show next. This eliminates the need for specific indexes in the static text.

Finally, to show/hide the button, we just make a computed property that compares the counter to the number of children:

<script setup>
  import { ref, computed, onMounted } from 'vue';
  const counter = ref(0);
  const expandable = ref(null);
  
  onMounted(() => {
    [...expandable.value.children].forEach((paragraph, index) => {
      if (index > 0) {
        paragraph.style.display = 'none';
      }
    });
  });
  
  function showNext() {
    counter.value++;
    expandable.value.children[counter.value].style.display = 'block';
  }
  
  const allShown = computed(() => counter.value === expandable.value?.children.length - 1);
</script>

<template>
    <p>Introduction text in future maybe</p>
  
    <div ref="expandable">
      <p>Long paragraph A</p>
      <p>Long paragraph B</p>
      <p>Long paragraph C</p>
    </div>
   
    <button v-if="!allShown" @click="showNext()">Click</button>
    <p>Following text</p>
</template>

Link to example

Leave a comment