router

先要在router,meta里给页面编号,通过监听route判断index的大小来确定是进入还是离开;

1
2
3
4
5
6
7
8
9
10
11
12
const routes = [
{
path: '/',
redirect: '/home'
},
{ path: '/home', component: () => import('../views/home/index.vue'), meta: { index: 0 } },
{ path: '/a', component: () => import('../views/a.vue'), meta: { index: 1 } },
{ path: '/b', component: () => import('../views/b.vue'), meta: { index: 2 } },
{ path: '/c', component: () => import('../views/c.vue'), meta: { index: 3 } },
{ path: '/d', component: () => import('../views/d.vue'), meta: { index: 4 } },
]

transition

通过vue的内置组件transition来做动画,这里有个注意点,vue3和vue2写法不一样

  • 在vue2中:

    1
    2
    3
    <transition :name="transitionName">
    <router-view class="view app-view"></router-view>
    </transition>
  • 在vue3中:

    1
    2
    3
    4
    5
    6
    <router-view class="router-view" v-slot="{ Component }">
    <transition :name="transitionName">
    <component :is="Component" />
    </transition>
    </router-view>

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

<template>
<router-view class="router-view" v-slot="{ Component }">
<transition :name="transitionName">
<component :is="Component" />
</transition>
</router-view>
</template>

<script>
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
export default {
name: 'App',
setup() {

const transition = ['slide-left', 'slide-right']
let transitionName = ref(transition[0])

const route = useRoute()

// 监控路由的变化
watch(
() => route.meta.index,
(newIndex, oldIndex) => {
if (newIndex > oldIndex) {
transitionName.value = transition[0]
} else {
transitionName.value = transition[1]
}
}
)

return { transitionName }
},
}
</script>

<style>

.router-view {
width: 100%;
height: 100%;
position: absolute;
top: 0;
bottom: 0;
margin: 0 auto;
overflow-y: auto;
overflow-x: hidden;
-webkit-overflow-scrolling: touch;
}

.slide-right-enter-active,
.slide-right-leave-active,
.slide-left-enter-active,
.slide-left-leave-active {
will-change: transform;
transition: all 500ms;
position: absolute;
}

.slide-right-enter {
opacity: 0;
transform: translate3d(-100%, 0, 0);
}

.slide-right-leave-active {
opacity: 0;
transform: translate3d(100%, 0, 0);
}

.slide-left-enter {
opacity: 0;
transform: translate3d(100%, 0, 0);
}

.slide-left-leave-active {
opacity: 0;
transform: translate3d(-100%, 0, 0);
}
</style>