把<router-view>嵌套在<transition>里,路由變化的時候,vue會為包裹頁面的div增加動畫樣式,我們要做的就是監聽路由變化、定義這些動畫樣式,以規定頁面到底怎么切換。具體樣式名通過transition的name屬性綁定。下面是在移動端模擬一般app界面的前進后退動畫:
<template>
<div id="app">
<transition :name="direction" >
<router-view class="appView"></router-view>
</transition>
</div>
</template>
<script>
export default {
name: "App",
data: () => ({
direction: "slide-right"
}),
watch: {
$route(to, from) {
const toDepth = to.path.split("/").length;
const fromDepth = from.path.split("/").length;
if (to.path == "/") {
this.direction = "slide-right";
} else if (from.path == "/") {
this.direction = "slide-left";
}else{
this.direction = toDepth < fromDepth ? "slide-right" : "slide-left";
}
}
}
};
</script>
<style>
.appView {
position: absolute;
width:100%;
transition: transform 0.3s ease-out;
}
.slide-left-enter{
transform: translate(100%, 0);
}
.slide-left-leave-active{
transform: translate(-50%, 0);
}
.slide-right-enter {
transform: translate(-50%, 0);
}
.slide-right-leave-active{
transform: translate(100%, 0);
}
</style>
具體動畫方式都能在$router的watch里面去定義。
建議增加router的scrollBehavior,定義來回切換的頁面位置。
吐槽下在移動端沒辦法配合手勢滑動來實現良好的router回退。
