1.出现这个warn的背景,请看代码:
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in" appear>
<component :is="Component"></component>
</transition>
</router-view>
2.问题原因分析:
由于:is="Component"属性会使所有的组件都渲染在这里,而外层是transition 虚拟组件,也就是说所有组件都会包裹在它里面,这是不允许的。
3.解决方案,推荐方案3:
-- 1.给每个组件分别加根节点div包裹起来:
<template>
<div class="about">
<h1>This is an about page</h1>
<button @click="toPath('/test')">去测试页面看看</button>
</div>
</template>
-- 2.
<template>
<router-view v-slot="{ Component }">
<transition >
<div>
<component :is="Component"></component>
</div>
</transition>
</router-view>
</template>
-- 3.最优方案:
<router-view v-slot="{ Component, route }">
<transition name="fade" mode="out-in">
<div :key="route.name">
<component :is="Component"></component>
</div>
</transition>
</router-view>
end:给出最终完整版,可以实现页面切换转场动画和缓存
<template>
<router-view v-slot="{ Component }">
<transition :name="$router.customRouterData.transitionName">
<keep-alive>
<div :key="$route.name">
<component
:is="Component"
v-if="$route.meta.keepAlive"
/>
</div>
</keep-alive>
</transition>
<transition :name="$router.customRouterData.transitionName">
<div :key="$route.name">
<component
:is="Component"
v-if="!$route.meta.keepAlive"
/>
</div>
</transition>
</router-view>
</template>
export default {
name: "app",
setup() {
return {};
},
};
</script>
<style lang="scss">
#app {
position: relative;
width: 100%;
height: 100%;
}
.slide_left-enter-active,
.slide_left-leave-active,
.slide_right-enter-active,
.slide_right-leave-active {
transition: all 0.3s;
position: absolute !important;
background-color: white;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 1;
}
.slide_left-enter-from,
.slide_right-leave-to {
opacity: 1;
transform: translateX(100%);
}
.slide_right-enter-from,
.slide_left-leave-to {
opacity: 1;
transform: translateX(-100%);
}
.slide_left-leave-to,
.slide_right-leave-to {
opacity: 0.3;
}
</style>