Subscribe on changes!

Transition doesn't work without key property in child component

avatar
Aug 23rd 2023

Vue version

3.2.45

Link to minimal reproduction

https://codesandbox.io/p/sandbox/nostalgic-bardeen-jvmjpv?file=%2Fsrc%2FApp.vue%3A30%2C38

Steps to reproduce

  <!-- keep-alive doesn't work -->
  <RouterView v-slot="{ Component, route }">
    <Transition name="fade">
      <div :key="route.fullPath" class="w-full h-full">
        <KeepAlive>
          <component
            :is="Component"
            v-if="route.meta.keepAlive"
            :key="route.fullPath"
          />
        </KeepAlive>
        <component :is="Component" v-if="!route.meta.keepAlive" />
      </div>
    </Transition>
  </RouterView>
  <!-- remove key in div, keep-alive works, but transition doesn't work -->
  <RouterView v-slot="{ Component, route }">
    <Transition name="fade">
      <div class="w-full h-full">
        <KeepAlive>
          <component
            :is="Component"
            v-if="route.meta.keepAlive"
            :key="route.fullPath"
          />
        </KeepAlive>
        <component :is="Component" v-if="!route.meta.keepAlive" />
      </div>
    </Transition>
  </RouterView>

Because the <Transition> component must have only one child element, and my routing component contains multiple root elements, So i have to add a <div> element in <Transition> component.

I need the <keep-alive> condition to work, not all routed pages need to cache data.

What is expected?

  • <keep-alive> can take effect conditionally.
  • <transition> works well.
  • Allows my routing component to contain multiple root elements.

What is actually happening?

<keep-alive> and <transition> cann't work at the same time.

System Info

System:
    OS: macOS 12.6.8
    CPU: (4) x64 Intel(R) Core(TM) i5-6500 CPU @ 3.20GHz
    Memory: 284.50 MB / 32.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.20.2 - ~/Library/Caches/fnm_multishells/34638_1692792377147/bin/node
    npm: 6.14.18 - ~/projects/AiFun-next/node_modules/.bin/npm
    pnpm: 8.6.12 - ~/Library/Caches/fnm_multishells/34638_1692792377147/bin/pnpm
    Watchman: 2023.05.08.00 - /usr/local/bin/watchman
  npmPackages:
    vue: ^3.2.45 => 3.2.47

Any additional comments?

No response

avatar
Aug 24th 2023

see https://router.vuejs.org/guide/advanced/transitions.html#Forcing-a-transition-between-reused-views

@edison1105 Thanks for your reply, how to use <keep-alive> conditionally at the same time?

avatar
Aug 24th 2023

@wtto00 maybe you need also add a key to <component :is="Component" v-if="!route.meta.keepAlive" />. please open an issue in router if it is not working

avatar
Aug 24th 2023

@edison1105 Thanks for your help. I opend a new issue in vue-router: https://github.com/vuejs/router/issues/1967

This issue is closed now.