How do I transition an element onMount in Vue?

Viewed 27

I have the following...

<template>
  <div class="layered-image fit">
    <img src="/img/Stars-background.svg" class="img1"/>
    <img ref="img2" src="/img/Mo-zen.svg" class="img2" />
  </div>
</template>
<script setup>
import {ref, onMounted} from "vue";
const img2 = ref(null);
onMounted(()=>{
  console.log("Setting the style");
  img2.value.style.bottom = "10%";
})
</script>
<style>
.img1 {
  position: absolute;
  bottom: 0;
  left: calc( 50% - 400px );
}
.img2 {
  position: absolute;
  bottom: 20%;
  transition: bottom 2s linear;
  right: calc( 50% - 280px );
}
.fit {
  height: 100%;
  width:100%;
}
</style>

I am just trying to move the image up from 20% to 10% over the course of 2 seconds after the component is mounted. However, this just seems to start the image at 10% with no transition.

How would I get the bottom to transition properly?

2 Answers

If you're trying to move the two images then I would recommend checking out Vue's built in GroupTransition.

This will allow you to give a name for your container and use this name with JavaScript hooks that Vue provides.

You can do something like this:

.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

So any element inside the list container will have those css applied to them during the component entering and leaving.

Related