Home » vue » Transition between the same component?

Transition between the same component?

Posted by: admin November 26, 2021 Leave a comment

Questions:
// Template
<transition name="fade">
    <my-component :my-prop="data[currentIndex]" />
</transition>

// CSS
.fade-enter-active, .fade-leave-active {
    transition: opacity .5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0;
}

I also have a button to change the current index and updating the data of the component.
this does not work and I assume it is because changing the data doesnt make it a new component which is needed to trigger the transition.

All the examples I have seen online is for switching betweenn different components, this work but I cant apply it since it all is for the same component.

Another solution I found was to create a bunch of components in a v-for and then having a v-show on the current one, but then I need absolute positioning to prevent the transitions from jumping and this does not seem like the way to do it.

I guess I could do the transitions in the script tag of the updated function or something but this seems like the wrong way when transitions are suppose to handle this for me. Am I missing something.

Answers:

Had the same problem yesterday! ^^”
It worked fine when I added a :key=”” attribute to my component (even if there is no prop called key in the child component).
Try with this :

<transition name="slide">
    <my-component :key="currentIndex" :my-prop="data[currentIndex]" />
</transition>

I don’t know yet why but I guess if a prop is an object, it dont detect the changes? Or maybe you must pass a key attribute (but I saw some examples not using key attribute…)
Tell me if it works 😉

Edit: I saw that you change the name of the transition and the style don’t include this name. Try the solution above with the default name and style (“fade”) https://vuejs.org/v2/guide/transitions.html