router-view提供插槽,可以在里面定义路由切换的动效。

/router/index.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { createRouter, createWebHistory } from "vue-router"
import type { RouteRecordRaw } from "vue-router"

declare module "vue-router" {
interface RouteMeta {
title: string,
transition: string
}
}

const routes: Array<RouteRecordRaw> = [
{
path: "/",
component: ()=> import("@/components/Login.vue"),
meta: {
title: "登录页面",
// 定义动效数据
transition: "animate__fadeIn"
}
},
{
path: "/index",
component: ()=> import("@/components/Index.vue"),
meta: {
title: "首页",
transition: "animate__bounceIn"
}
}
]

const router = createRouter({
// 路由的模式
history: createWebHistory(),
// 路由信息
routes
})

router.beforeEach((to,from,next)=> {
// 这里可以读到meta
document.title = to.meta.title
next()
})

export default router

App.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<template>
<!-- Vue-Router4写法(插槽) -->
<!-- route:当前路由信息 Component:当前Vnode -->
<router-view #default="{route,Component}">
<transition :enter-active-class="`animate__animated ${route.meta.transition}`">
<component :is="Component"></component>
</transition>
</router-view>
</template>

<script setup lang="ts">
import "animate.css"

</script>

<style>
* {
padding: 0;
margin: 0;
}

html,
body,
#app {
height: 100%;
overflow: hidden;
}
</style>