vue3如何实现路由动画?
先在App.vue中写上
<router-view v-slot="{ Component, route }"> <transition :name="route.meta.transition"> <component :is="Component" /> </transition> </router-view>
然后App.vue上的样式为
.fade-enter-from, .fade-leave-to { /*定义进入开始和离开结束的透明度为0*/ opacity: 1; } .fade-leave-to { transform: translateX(-100%); } .fade-enter-to { transform: translateX(0); } .fade-enter-to, .fade-leave-from { /*定义进入结束和离开开始的透明度为1*/ opacity: 1; } .fade-leave-active, .fade-enter-active { transition: all 0.5s ease-out; } .defa-enter-from, .defa-leave-to { /*定义进入开始和离开结束的透明度为0*/ opacity: 1; } .defa-leave-to { transform: translateX(100%); } .fade-enter-to { transform: translateX(-100%); } .defa-enter-to, .defa-leave-from { /*定义进入结束和离开开始的透明度为1*/ opacity: 1; } .defa-leave-active, .defa-enter-active { transition: all 0.5s ease-out; }
最后在
router的index.js写以下代码
router.beforeEach((to, from) => { var routlist = [] routes.forEach(item => { routlist.push(item.path) }) routlist.forEach((item, index) => { if (from.path == item) { if (routlist.splice(index).includes(to.path)) { to.meta.transition = "fade" } else { to.meta.transition = "defa" } } }) })