vue router 配合transition 切换动画
把<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回退。