首页 > 技术文章 > Vue-router 进阶

the-last 2019-08-21 23:01 原文

1、 路由的元信息

在定义路由的时候,可以定义 meta 字段

children: [
     {
         path: 'bar',
         component: Bar,

         // a meta field  元信息
         meta: { requiresAuth: true }  这里路由提示需要认证
     }
 ]

 

如何使用这个meta呢?

 

路由中匹配到的路径都被称为路由记录,每个路由记录都会被存在 $route.metched 中

所以,可以通过访问$route.metched 遍历数组,获得meta值。

在 路由守卫的参数中也有对应的meta值

router.beforeEach((to, from, next) => {

 if (to.matched.some(record => record.meta.requiresAuth)) {

   // 检查登录状态
   // 未登录,就跳到登录页

   if (!auth.loggedIn()) {
     next({
       path: '/login',
       query: { redirect: to.fullPath }
     })
   } else {
     next()
   }
 } else {
   next() // 确保一定要调用 next()
 }
})

 

 

2、 基于路由的动画效果

 

 

 

3、 获取数据

 

一般是两种:

 

1,在路由跳转后组件渲染时获取数据,可以loading,每个视图可以用自己的loading

2,可以在 beforeRouteEnter  beforeRouteUpdate 中获取数据,和路由同步或者获取不到数据后不next().

 

4、 滚动行为

 

切换路由路径,对应不同页面,同时vue-router还可以保留滚动的位置信息,但仅限于支持pushState的浏览器。

scrollBehavior (to, from, savedPosition) {

    // 1,返回跳转到的指定的页面的位置
    if (to.hash) {
        return{
            selector:to.hash
        };
    }
    // 2, 返回保留的位置
    if (savedPosition) {
         return savedPosition;
    }

    // 3, 返回置顶,也是 default
    return{ x:0, y:0 };
}

 

5、 异步滚动 (2.8.0新增)

返回一个promise 得出一个预期的位置

scrollBehavior (to, from, savedPosition) {

    return new Promise(resolve, reject) {
        setTimeout( () => {
             resolve({x: 0, y: 0});
        },  2000);    // 接收 promise 传值
    }
}

 

6、 组件懒加载方法  4 种

6.1 、es6 方式 2种

声明高阶函数

const apply = name => import(`../components/${name}.vue`);

函数引入组件

()=> import(`../components/HelloWorld.vue`);  

 

6.2 、commonJS 方式  2种

直接引用

resolve => require.ensure([], () => resolve(require('../components/HelloWorld.vue')))

函数引入

component(resolve) { require(['../components/' + name + '.vue'], resolve) }

 

推荐阅读