Jump to content
Search Community

Vue targeting dynamic created elements for animation

JLernDesign test
Moderator Tag

Go to solution Solved by Rodrigo,

Recommended Posts

I'm pretty new to Vue so hopefully this makes sense. I'm trying to figure out why I can animate a static element using the class name selector, but if I am creating dynamic elements they cannot be targeted by class name. Been searching all over the place and can't seem to find a good answer to this. I tried to use a ref for each element as well and that didn't work either. Thanks for the help!

<script setup>
import { onMounted } from 'vue';
import BlogThumb from './components/BlogThumb.vue';
import gsap from 'gsap';

onMounted(() => {
  // this selector works
  gsap.to('.wrapper', { duration: 0.5, opacity: 1 });
  
  // this selector does not work (console error: GSAP target .blog-thumb not found)
  gsap.to('.blog-thumb', { opacity: 1, stagger: 0.2 });
});
</script>

<template>
  <div class="wrapper">
    <div class="blog-grid">
      <BlogThumb v-for="post in posts" :key="post.id" class="blog-thumb" />
    </div>
  </div>
</template>

 

Link to comment
Share on other sites

  • Solution

Hi,

 

I’m not in front of my computer right now, but mainly the issue stems from when the gasp  instances are created, in this case when the component is mounted so the elements are the ones present at that point.

 

You should create a watcher and create the animations when the array is updated (you’re using a v-for directive so I’ll assume that an array is involved).

 

https://vuejs.org/guide/essentials/watchers.html
 

Hopefully this helps.

Happy Tweening!

  • Like 1
Link to comment
Share on other sites

Thanks @Rodrigo for pointing me in the right direction. I discovered I also need to use nextTick() with the watcher before the instances can be accessed. This is the code I landed on that is working now. Appreciate the help!

 

watch(posts, (newData) => {
  if (newData.length > 0) {
    nextTick(() => {
      gsap.to('.blog-thumb', {opacity: 1, stagger: 0.2 });
    });
  }
});

 

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...