移动端页面切换一般都具有动画,我们既然要做混合开发,做完之后还是不能看起,所以我们基于vue-router扩展了一个页面切换push和pop的动画。这是一篇比较硬核的帖子,作者花了不少精力来写
先上效果图路由切换动画.gif
再贴核心代码router文件夹下,新建文件,实现如下:
/***router扩展,页面切换动画*///负责SessionStorage存储路由历史。constSessionStorage_key_Router_Extend_History=SessionStorage_key_Router_Extend_HistoryfunctiontransitionExtend(orgin){//通过原路由对象创建一个新的对象letrouter=(orgin)//扩展对象,保存当前栈数组和过渡动画名称={transitionName:,history:[]}//路由位置字符串在数组中的位置=function(path){letarrLen=(leti=arrLen-1;i=0;i--){if([i]==path){returni;}}return-1;}//添加历史路由去路由数组=function(path){(path)(SessionStorage_key_Router_Extend_History,());}//历史路由数组移除某个路由,n为参数可以移除多个=function(n=1){if(n0){for(leti=0;in;i++){()}(SessionStorage_key_Router_Extend_History,());}}//初始化,为了页面刷新能恢复路由记录等=function(toPath){//当存储了routerpaths,读取并赋值letarrStrarrStr=(SessionStorage_key_Router_Extend_History);if(arrStr&&arrStr!=undefined){letarr=(arrStr)if((arr)&&0){//进入页面=arr;}else{//新进入页面=[](toPath)}}else{//新进入页面=[](toPath)}//存储为了恢复(SessionStorage_key_Router_Extend_History,());}//push修改路由历史,并设置动画=function(){letlocation=arguments[0]if(typeoflocation==string){(location)}else{()}=slide_leftrouter.__proto__.(this,...arguments)};//replace修改路由历史,并设置动画=function(){()letlocation=arguments[0]if(typeoflocation==string){(location)}else{()}=slide_leftrouter.__proto__.(this,...arguments)};//go修改路由历史,并设置动画=function(n){if(n0){//禁止使用,这种情况比较复杂,使用较少,先忽略(暂不支持前进!);return;}(-n)=slide_rightrouter.__proto__.(this,n)};//back修改路由历史,并设置动画=function(){()=slide_rightrouter.__proto__.(this,-1)};=function(){//禁止使用,这种情况比较复杂,使用较少,先忽略(暂不支持!);return;};/***按钮前进后退处理处理*返回:测滑返回,微信返回按钮,web返回按钮,以及android物理返回,android测滑返回*前进:微信上的前进按钮,web前进*//前进这里有个坑,待解决,先忽略**/=function(toPath,fromPath){if(!=){//没有数据意味着从,其他操作方式得到的路由变化return;}lettoIndex=(toPath)if(toIndex==-1||-toIndex!=2){//不存在,并且历史(toPath)=slide_left}else{()=slide_right}}//是否已经初始化letisInit=false;//跳转之前((to,from,next)={if(isInit){(,)}else{isInit=true;()}next();})//跳转之后((to,from)={setTimeout(()={//使用动画之后立即移除=},300)})returnrouter}exportdefaulttransitionExtend使用1、对全局router对象进行扩展,一般在router/里面
//引入扩展函数importtransitionExtendfrom./transition-extend;//对router对象扩展router=transitionExtend(router)//export扩展后的路由对象exportdefaultrouter
2、为router-view添加过渡动画,一般在里面
templaterouter-viewv-slot={Component}transition:name=$:is=Component//transition/router-view/templatescriptexportdefault{name:app}/scriptstylelang=stylusscopedtype=text/stylus#app{positionrelative;width100%;height100%;}.slide_left-enter-active,.slide_left-leave-active,.slide_right-enter-active,.slide_right-leave-active{transition:all0.3s;positionabsolute!important;background-colorwhite;left0;right0;top0;bottom0;z-index1;}.slide_left-enter-from,.slide_right-leave-to{opacity1;transform:translateX(100%);}.slide_right-enter-from,.slide_left-leave-to{opacity1;transform:translateX(-100%);}.slide_left-leave-to,.slide_right-leave-to{opacity0.3;}/style3、现在我们正常使用路由切换就可以看到路由动画了,赶快试试吧。
this.$({path:/test})