最近再写页面的时候,感觉页面之间的切换有点生硬,所以查了一下文档看见了transition这个组建,很实用,故此在这里跟大家分享一下
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
1、解决这个问题的难点就是如何来确定路由是前进还是后退的问题,下面是解决的方案
a) 我们需要给各个页面定义层级,在切换路由时判断用户是进入哪一层页面,如果用户进入更高层级那么做前进动画,如果用户退到低层级那么做后退动画.
router/index.js
1 import VueRouter from 'vue-router' 2 import Home from '../components/home/home' 3 import User from '../components/user/user' 4 var router = new VueRouter({ 5 routes:[{ 6 name:'test', 7 path:'/', 8 meta:{index:0}, // meta对象的index用来定义当前路由的层级,由小到大,由低到高 9 component:{template:'<div>test</div>' }}, 10 { 11 name:'home', 12 path:'/home', 13 meta:{index:1}, 14 component:Home 15 }, 16 { 17 name:'user', 18 path:'/user/:id', 19 meta:{index:2}, 20 component:User 21 }] 22 } 23 }); 24
监控路由跳转,判断切换页面之间的层级关系,并以此来判断路由前进或者后退.
1 <template> 2 <div id="app"> 3 <transition :name="transitionName"> 4 <router-view></router-view> 5 </transition> 6 </div> 7 </template> 8 <script> 9 export default { 10 name: 'App', 11 data () { 12 return { 13 transitionName:'' 14 } 15 }, 16 watch: { 17 // 使用watch 监听$router的变化 18 $route (to, from) { 19 // 如果to索引大于from索引,判断为前进状态,反之则为后退状态 20 if (to.meta.index > from.meta.index){ 21 // 设置动画名称 22 this.transitionName = 'slide-left'; 23 } else{ 24 this.transitionName = 'slide-right'; 25 } 26 } 27 } 28 } 29 </script> 30
编写slide-left 和 slide-right 类的动画
1 .slide-right-enter-active, 2 .slide-right-leave-active, 3 .slide-left-enter-active, 4 .slide-left-leave-active { 5 will-change: transform; 6 transition: all 500ms; 7 position: absolute; 8 }.slide-right-enter { 9 opacity: 0; 10 transform: translate3d(-100%, 0, 0); 11 }.slide-right-leave-active { 12 opacity: 0; 13 transform: translate3d(100%, 0, 0); 14 }.slide-left-enter { 15 opacity: 0; 16 transform: translate3d(100%, 0, 0); 17 }.slide-left-leave-active { 18 opacity: 0; 19 transform: translate3d(-100%, 0, 0); 20 }