Jump to content
Search Community

Best way to integrate Draggable into the Vue component lifecycle

stefanobartoletti test
Moderator Tag

Go to solution Solved by Rodrigo,

Recommended Posts

This is not strictly a help request (my integration is working correctly), but more like a desire to understand how things work. And,  it is probably also more generic and not related only to Draggable, but more generally even to  other GSAP plugins.

 

I've integrated Draggable into one Vue component, this is a schematic overview of my implementation:

 

<template>
  <section>
   <!-- my component template -->
  </section>
</template>

<script setup>
const items = ref([]) // Target items, full code omitted for brevity
const { Draggable } = useGsap() // Import gsap from a dedicated composable

onMounted(() => {
  Draggable.create(items.value, {
    // Draggable options
  })
})

onUnmounted(() => {
  Draggable.kill()
})
</script>

 

Everything is working correctly on the front-end, and  also Draggable.kill() should be hooked correctly on the component lifecycle.

I've also tried another implementation, similar to the one often suggested when using gsap.context, just like this:

<script setup>
const ctx = ref()
const items = ref([]) // Target items, full code omitted for brevity
const { Draggable } = useGsap() // Import gsap from a dedicated composable

onMounted(() => {
  ctx.value = Draggable.create(items.value, {
    // Draggable options
  })
})

onUnmounted(() => {
  ctx.value.revert()
})
</script>

 

And it seems to work correctly, just like in the previous example.

 


Since these two solutions are effectively working in the same way on the frontend, are there some reasons to prefer one over another? Under the hood, what are the differences between them?

Thanks :-)

 

 

Link to comment
Share on other sites

  • Solution

Hi,

 

There are no issues in either of the approaches you posted actually. For a matter of simplicity, in the case you end up with a bunch of instances besides the Draggable one, you can use GSAP Context, like that with the revert() method GSAP Context does cleanup of every instance in it's scope for you.

 

Finally there is no need to make the GSAP Context instance a reactive property:

let ctx;

onMounted(() => {
  ctx = gsap.context(() => {
    ...
  });
});

onUnmounted(() => {
  ctx && ctx.revert();
});

Hopefully this helps.

Happy Tweening!

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...