Nuxt3/Vue3插槽内容变化时如何使用transition过渡效果
Nuxt3/Vue3 全局布局插槽内容过渡效果实现
失效原因
Vue <transition> 组件仅在直接子元素发生挂载、卸载操作时触发动画。当前写法里包裹<slot />的div没有绑定动态标识,路由切换时这个DOM节点会被框架直接复用,仅替换内部插槽的渲染内容,transition无法感知到子节点变更,所以不会触发动画。全局default布局本身不重载的逻辑符合预期,不需要调整布局渲染规则。
修复步骤
- 删除slot外层冗余的嵌套transition组件,多层同效果transition嵌套会导致动画时序冲突
- 给slot的直接承载节点绑定动态key,路由切换时key变化会让Vue判定为节点切换,transition即可正常捕获进出场时机
- 保留原有
mode="out-in"配置,保证旧内容完全离场后新内容再入场,避免布局偏移
修正后代码
<template> <div class="bg-darkSecondary dark:bg-black h-screen"> <teleport to="body"> <transition name="modal-fade"> <div v-if="uiStore.functionLoading" class="modal-backdrop"> <UiBaseSpinner></UiBaseSpinner> </div> </transition> </teleport> <UiNav class="dark:bg-darkBg dark:text-darkSecondary" /> <div class="flex dark:bg-black bg-darkSecondary"> <transition name="sidebar" mode="out-in"> <UiSideNav v-if="uiStore.sidebar" /> </transition> <transition name="fade" mode="out-in"> <div v-if="!uiStore.appLoading" class="flex-grow max-w-full max-h-full bg-darkSecondary dark:bg-black trans" > <!-- 绑定路由fullPath作为动态key,移除冗余嵌套transition --> <div :key="$route.fullPath"> <slot /> </div> </div> <div v-else class="flex flex-grow mt-40 justify-center trans"> <UiBaseSpinner /> </div> </transition> </div> <UiFooter class="fixed bottom-0" /> </div> </template>
扩展说明
如果需要插槽内非路由触发的数据更新也触发过渡,只需要把节点上的key替换为自定义的、随内容更新同步变化的唯一值即可,比如列表刷新时的时间戳、数据版本号等,不需要修改布局其他逻辑。
内容的提问来源于stack exchange,提问作者Luke Longo
相关产品推荐
相关产品推荐

