Vue-router 进阶

一、 路由的元信息vue

在定义路由的时候,能够定义 meta 字段es6

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

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

 

如何使用这个meta呢?vue-router

 

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

因此,能够经过访问$route.metched 遍历数组,得到meta值。promise

在 路由守卫的参数中也有对应的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()
 }
})

 

 

二、 基于路由的动画效果app

 

 

 

三、 获取数据异步

 

通常是两种:函数

 

1,在路由跳转后组件渲染时获取数据,能够loading,每一个视图能够用本身的loading动画

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

 

四、 滚动行为

 

切换路由路径,对应不一样页面,同时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 };
}

 

五、 异步滚动 (2.8.0新增)

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

scrollBehavior (to, from, savedPosition) {

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

 

六、 组件懒加载方法  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) }
相关文章
相关标签/搜索