目录
网页标题是通过<title>来显示的,但是一个SPA应用只有一个HTML,切换不同页面时,标题并不会改变
怎么修改?
修改src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
const Home = ()=>import('../components/Home')
const About = ()=>import('../components/About')
const User = ()=>import('../components/User')
const HomeNews = ()=>import('../components/HomeNews')
const HomeMessage = ()=>import('../components/HomeMessage')
const Profile = ()=>import('../components/profile')
Vue.use(Router)
const routes = [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
component: Home,
children: [
{
path: '',
redirect: 'news'
},
{
path: 'news',
component: HomeNews
},
{
path: 'message',
component: HomeMessage
}
],
meta: {
title: '首页'
}
},
{
path:'/about',
component: About,
meta: {
title: '关于'
}
},
{
path: '/user/:user_id',
component: User,
meta: {
title: '用户'
}
},
{
path: '/profile',
component: Profile,
meta: {
title: '档案'
}
}
]
const router = new Router({
routes,
mode: 'history',
linkActiveClass:'active'
})
router.beforeEach((to, from, next) => {
document.title = to.matched[0].meta.title
next()
})
export default router
效果
vue-router提供的导航守卫主要用来监听路由的进入和离开
vue-router提供的beforeEach和afterEach的钩子函数,它们会在路由改变前和改变后触发
在路由映射routes中添加meta,在里面定义了标题
调用了beforeEach方法,三个参数:
to: 即将要进入的目标路由对象
from: 当前导航即将要离开的路由对象
next: 调用该方法后,才能进入下一个钩子
这两是全局守卫
此外,还有路由独享的守卫,组件内的守卫
官网