Vue页面跳转动画效果的实现方法

2020-06-13 10:22:45易采站长站整理

</router-link>

用在调用router.push()中也是一回事:


this.$router.push({ name: 'Order', params: { userId: 123 }})

3、$route.params

对象(object)。路由跳转携带参数:


this.$router.push({ name: 'Order', params: { userId: 123 }})
console.log(this.$route.params.userId); //123

4、$route.query

对象(object)。可访问携带的查询参数:


this.$router.push({name: 'login', query:{name: 'userName'}});
this.$route.query.name; //you
//此时路由为:http://example.com/#/login?name=userName。

5、$route.redirectedFrom

字符串(string)。重定向来源:

如:{ path: ‘*’,redirect: {name: ‘hello’}}
 此时访问不存在的路由http://example.com/#/a会重定向到hello,
在hello访问this.$route.redirectedFrom; 输出“/a”。

6、$route.matched

数组(array)。当前路由下路由声明的所有信息,从父路由(如果有)到当前路由为止。

7、$route.hash

字符串(string)。当前路径的hash值。

四、vue监听$route的方式


watch:{‘$route' (to, from) {}}

route 的变化。watch中监听的对象默认回调函数中的参数值就是newVal,oldVal。作为 $route 属性来说当然也就是 to 和 from 的概念了。

Vue用router.push(传参)跳转页面,参数改变,在跳转后的路由观察路由变化,进行页面刷新,可对“from->to”的过程设置动画效果。

该功能的难点就在于怎样获取“上一页”和“下一页”,即怎样分辨是“前进”还是“后退”?

例:


// watch $route 决定使用哪种过渡
watch:{
'$route' (to, from) {
//此时假设从index页面跳转到pointList页面
console.log(to); // "/pointList"
console.log(from); // “/index”
const routeDeep = ['/', '/index','/pointList', '/settLement'];
const toDepth = routeDeep.indexOf(to.path)
const fromDepth = routeDeep.indexOf(from.path)
this.transitionName = toDepth > fromDepth ? 'fold-left' : 'fold-right'
}
},

to、from是最基本的路由对象,分别表示从(from)某个页面跳转到(to)另一个页面,to.path(表示要跳转到的路由地址),from.path同理。

定义routeDeep数组,将路由目录按层级依次排序(暂不考虑嵌套路由的情况),复杂单页应用里,同一层级(如同一页面上的多个导航按钮)顺序随意,然后依次排列每个导航的下一页、下下页…即保证每个“上一页”在“下一页”前面。

总结下来就是:按照routeDeep数组里定义的路由目录的顺序,“toDepth > fromDepth”表示“上一页”跳转到“下一页”,同理可由此判断是“前进”还是“后退”。