在进行路由跳转的时候我们也可以设置一些动效,让整个过程看起来没那么枯燥(这里使用animate.css动画库)
import { createApp, toRaw } from 'vue'
import router from './router'
import App from './App.vue'
// 引入动画库
import 'animate.css'
const app = createApp(App)
app.use(router)
app.mount('#app')
<template>
<div>
<router-view #default="{ route, Component }">
<transition
:enter-active-class="`animate__animated animate__backInRight`"
>
<component :is="Component"></component>
</transition>
</router-view>
</div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
</script>
<style scoped></style>
router-view有一个默认作用域插槽,接收两个变量route和Component,route包含跳转时的一些路由信息,Component则是VNode,可通过动态组件展示在页面上。上图这样的处理方式让所有的路由都使用animate__backInRight这个动画,如果想让不同路由组件使用不同动画可以在meta中定义动画名
<template>
<div>
<router-view #default="{ route, Component }">
<!-- 定义动画类名,从route.meta中取 -->
<transition
:enter-active-class="`animate__animated ${route.meta.transition}`"
>
<component :is="Component"></component>
</transition>
</router-view>
</div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
</script>
<style scoped></style>
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
// declare声明模块防止类型报错
declare module 'vue-router' {
interface RouteMeta {
transition: string
}
}
const routes: Array<RouteRecordRaw> = [
{
path: '/',
meta: {
// 定义动画名
transition: 'animate__backInRight',
},
component: () => import('../components/login.vue'),
},
{
path: '/reg',
component: () => import('../components/reg.vue'),
},
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
router.beforeEach((to, from, next) => {
next(true)
})
export default router