Location>code7788 >text

Vue3 After adding animation to a route jump, the page jerks up and down when jumping.

Popularity:463 ℃/2024-12-19 20:14:23

This issue needs to be addressed in the following two steps:

  • Check if the jittered page component has multiple root nodes
  • Add css style for leaving transitionv-leave-to: {display: none}

Step 1 (check if the jittered page component has multiple root nodes)

I'm adding an animation for the route jump as follows:


<template>
    <router-view v-slot="{Component}">
        <transition name="fade" mode="out-in">
            <component :is="Component"></component>
        </transition>
    </router-view>
</template>

<style scoped lang="less">
    .fade-enter-active,
    .fade-leave-active {
        transition: all .5s;
    }

    .fade-leave-from {
        opacity: 0;
        transform: translateX(30px);
    }

    .fade-enter-from {
        opacity: 0;
        transform: translateX(-30px);
    }
</style>

After adding it, I found that some pages can load the animation normally, and some pages have the jitter problem, then I found that the console has the following warning message:

The questions are explained below:

The warning message indicates that you are using theVue (used form a nominal expression)<Transition> component when encountering problems.<Transition> component requires that the content it wraps around can only have one root element, this is because theVue The transition effects need to be animated for individual elements.

If your<Transition> The component renders multiple elements inside theVue It will not be possible to apply animation effects to these elements, so this warning will be thrown.

So if you see any page component with jitter, check if the code has more than one root node, for example, we found that theComponent A The page has multiple root nodes as follows:

Old code:


<template>
    <p> First line </p>
    <p> second line </p>
</template>

New code:


<template>
    <div>
        <p> First line </p>
        <p> second line </p>
    </div>.
</template>

utilizationdivPackage of twoptag, ensuring that there is only one root node inside the component

Step 2 (add leave transition css style v-leave-to)

We add another line in the style to leave the transition style, so that the page does not take up space can be, the code is as follows,:

.fade-leave-to {
    display: none;
}