关于使用vue3时 切换路由 transition 失效问题
这个问题在vue2中可能不会遇到,但是在vue3中大部分同学都会碰到。因为在vue3中是支持多个根节点的,也就是片段 fragments!在组件使用多个根节点时就会遇到切换路由 transition 失效问题。
首先我们看路由切换相关代码:
<template>
<router-view v-slot="{ Component }">
<transition
name="fade-transform"
mode="out-in"
enter-from-class="fade-transform-enter"
>
<keep-alive :include="cacheList">
<component :is="Component" :key="key" />
</keep-alive>
</transition>
</router-view>
</template>
在组件使用多个根节点时切换路出现 transition 失效问题。
组件代码:
<template>
<div class="header">header</div>
<div class="body">body</div>
</template>
需要改成一个根节点,页面跳转动画才能正常执行。
修改代码后:
<template>
<div class="content">
<div class="header">header</div>
<div class="body">body</div>
</div>
</template>
vue 源码中对这块部分也是有检测说明的, transition 只期望有一个子元素或组件。 大家使用的时候需要注意一下。
describe('Transition multi children warnings', () => {
function checkWarning(
template: string,
shouldWarn: boolean,
message = `<Transition> expects exactly one child element or component.`
) {
const spy = vi.fn()
compile(template.trim(), {
hoistStatic: true,
transformHoist: null,
onError: err => {
spy(err.message)
}
})
if (shouldWarn) expect(spy).toHaveBeenCalledWith(message)
else expect(spy).not.toHaveBeenCalled()
}
test('warns if multiple children', () => {
checkWarning(
`
<transition>
<div>hey</div>
<div>hey</div>
</transition>
`,
true
)
})
...
})