说说 vue-router 组件的高级应用

版权声明:如果喜欢,就点个赞呗 O(∩_∩)O~ https://blog.csdn.net/deniro_li/article/details/89046975

1 动态设置页面标题

页面标题是由 <title></title> 来控制的,因为 SPA 只有一个 HTML,所以当切换到不同的页面时,标题是不会发生变化的。必须通过 JavaScript 来修改 <title></title> 中的内容:

window.document.title ='xxx'

有一种思路是在每个页面的 *.vue 的 mounted 钩子函数中,通过 JavaScript 来修改 <title></title> 中的内容。这种方式固然可行,但如果页面很多,就会显著增加维护成本,而且修改逻辑都是一样的。有没有更好的方法呢?

我们可以利用 vue-router 组件的导航钩子 beforeEach 函数,在路由发生变化时,统一设置。

import VueRouter from 'vue-router';
...

//加载 vue-router 插件
Vue.use(VueRouter);

/*定义路由匹配表*/
const Routers = [{
    path: '/index',
    component: (resolve) => require(['./router/views/index.vue'], resolve),
    meta: {
        title: '首页'
    }
},
    //一次性加载
    // {
    //     path: '/index',
    //     component: require('./router/views/index.vue')
    // },
    {
        path: '/about',
        component: (resolve) => require(['./router/views/about.vue'], resolve),
        meta: {
            title: '关于'
        }
    },
    {
        path: '/article/:id',
        component: (resolve) => require(['./router/views/article.vue'], resolve)
    }
    ,
    {//当访问的页面不存在时,重定向到首页
        path: '*',
        redirect: '/index'
    }
]

//路由配置
const RouterConfig = {
    //使用 HTML5 的 History 路由模式
    mode: 'history',
    routes: Routers
};
//路由实例
const router = new VueRouter(RouterConfig);

//动态设置页面标题
router.beforeEach((to, from, next) => {
    window.document.title = to.meta.title;
    next();
})

new Vue({
    el: '#app',
    router: router,
    render: h => h(Hello)
})

我们在路由匹配表中,为那些需要标题的页面,配置了 meta title 属性:

meta: {
        title: 'xxx'
}

然后在 beforeEach 导航钩子函数中,从路由对象中获取 meta title 属性,用于标题设置。beforeEach 有三个入参:

参数 说明
to 当前导航,即将要进入的路由对象。
from 当前导航,即将要离开的路由对象。
next 调用 next() 之后,才会进入下一步。

效果:

2 长页面跳转自动返回顶端

假设第一个页面较长,用户滚动查看到底部,这时如果又跳转到另一个页面,那么滚动条是会默认停在上一个页面的所在位置的。这种场景比较好的设计是:跳转后会自动返回顶端。这可以通过 afterEach 钩子函数来实现,代码如下:

router.afterEach((to, from, next) => {
    window.scrollTo(0, 0);
});

组合使用 beforeEach 与 afterEach,还可以实现:从一个页面跳转到另一个页面时,出现 Loading 动画,当新页面加载后,再结束动画。

3 登陆验证

某些页面设置了权限,只有账号登陆过,才能访问;否则跳转到登录页。假设我们使用 localStorage 来判断是否登陆。

HTML5 的 localStorage 特性,用于本地存储。它的出现,解决了 cookie 存储空间不足的问题 cookie 中每条 cookie 的存储空间只有 4k) ,而 localStorage 中一般是 5M,这在不同的浏览器中 大小略有不同 。

router.beforeEach((to, from, next) => {
    if (window.localStorage.getItem('token')) {
        next();
    } else {
        next('/login');
    }
});

next() 入参,如果是 false,会不导航;如果为路径,则会导航到指定路径下的页面。

猜你喜欢

转载自blog.csdn.net/deniro_li/article/details/89046975
今日推荐