Home > front end >  How do I transition an element onMount in Vue?
How do I transition an element onMount in Vue?

Time:09-07

I have the following...

<template>
  <div >
    <img src="/img/Stars-background.svg" />
    <img ref="img2" src="/img/Mo-zen.svg"  />
  </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?

CodePudding user response:

Hi i think the best way to play with transition is to see the documentation and not to play with pure css if unless this is what you need and what is the best to play with it :

https://vuejs.org/guide/built-ins/transition.html

However for your example i think you are mistaking variables and refs

But like this post say: Smooth CSS transition from position relative to position absolute with :hover::after

You cannot use transition on position

CodePudding user response:

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