页面标题是由 <title></title>
来控制的,由于 SPA 只有一个 HTML,因此当切换到不一样的页面时,标题是不会发生变化的。必须经过 JavaScript 来修改 <title></title>
中的内容:vue
window.document.title ='xxx'
复制代码
有一种思路是在每一个页面的 *.vue 的 mounted 钩子函数中,经过 JavaScript 来修改 <title></title>
中的内容。这种方式当然可行,但若是页面不少,就会显著增长维护成本,并且修改逻辑都是同样的。有没有更好的方法呢?vue-router
咱们能够利用 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 属性:bash
meta: {
title: 'xxx'
}
复制代码
而后在 beforeEach 导航钩子函数中,从路由对象中获取 meta title 属性,用于标题设置。beforeEach 有三个入参:cookie
参数 | 说明 |
---|---|
to | 当前导航,即将要进入的路由对象。 |
from | 当前导航,即将要离开的路由对象。 |
next | 调用 next() 以后,才会进入下一步。 |
效果:app
假设第一个页面较长,用户滚动查看到底部,这时若是又跳转到另外一个页面,那么滚动条是会默认停在上一个页面的所在位置的。这种场景比较好的设计是:跳转后会自动返回顶端。这能够经过 afterEach 钩子函数来实现,代码以下:函数
router.afterEach((to, from, next) => {
window.scrollTo(0, 0);
});
复制代码
组合使用 beforeEach 与 afterEach,还能够实现:从一个页面跳转到另外一个页面时,出现 Loading 动画,当新页面加载后,再结束动画。动画
某些页面设置了权限,只有帐号登录过,才能访问;不然跳转到登陆页。假设咱们使用 localStorage 来判断是否登录。ui
HTML5 的 localStorage 特性,用于本地存储。它的出现,解决了 cookie 存储空间不足的问题 cookie 中每条 cookie 的存储空间只有 4k) ,而 localStorage 中通常是 5M,这在不一样的浏览器中 大小略有不一样 。spa
router.beforeEach((to, from, next) => {
if (window.localStorage.getItem('token')) {
next();
} else {
next('/login');
}
});
复制代码
next() 入参,若是是 false,会不导航;若是为路径,则会导航到指定路径下的页面。