router和route
在组件内打印出this.$router和在main.js中打印出的router是同一个东西
但是在组件里打印出route和router就不一样了
route是组件自己配置的路由。
所有的组件都继承自Vue的原形
导航守卫
导航守卫就是路由跳转过程中的一些钩子函数,路由跳转时一个大的过程,这个过程可以细分为跳转前中后等过程,每个过程都有一个函数,这个函数,能让你操作一些其他的事。
vue-router提供的导航守卫主要用来监听路由的进入和离开的
vue-router提供了beforeEach和afterEach的钩子函数,它们会在路由即将改变前和改变后的触发
beforeEach,前置钩子的三个参数解析:
to:即将要进入的目标的路由对象
from:当前导航即将要离开的路由对象
next:调用该方法后,才能进入下一个钩子
后置守卫(钩子)
afterEach,只有两个参数to,from。
生命周期函数
1,created(){}
组件被创建出来之后会回调这个生命周期函数。
2,mounted(){}
当组件被挂载到dom上面之后,就在这里回调这个生命周期函数。
3,updated(){}
当页面发生刷新,就会在这里执行update。
在前面的实例中,所有的跳转的名称都是index.html上的标题的名称,那么当跳转到首页时,能不能将名字改为首页,跳转到关于时,能不能将标题改为关于?
答案是可以:利用created函数。在每个组件都使用这个函数。
export default {
name: "About",
created() {
document.title = "关于";
},
};
这是局部导航守卫。还可以使用全局导航守卫。
全局导航应用步骤:
1,在所有的路由中用meta属性添加关于标题的信息:
const routes = [
{
path: '/',
// 重定向
redirect: '/home'
},
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
// 一个映射关系就是一个对象
{
path: '/home',
name: 'Home',
// component: Home
component: Home,
meta: {
title: '首页'
},
children: [
{
path: '/',
redirect: 'news'
},
{
// 不加/
path: 'news',
component: HomeNews
},
{
path: 'message',
component: HomeMessage
}
]
},
{
path: '/about',
name: 'About',
meta: {
title: '关于'
},
component: About
},
{
path: '/user/:userId',
name: 'User',
meta: {
title: '用户'
},
component: User
},
{
path: '/profile',
name: 'Profile',
meta: {
title: '档案'
},
component: Profile
}
]
2,在下面使用beforeEach方法
router.beforeEach((to, from, next) => {
// 从from跳转到to
document.title = to.meta.title;
console.log(to);
next()
})
但是在首页中有点错误,因为路由的嵌套,
打印出的to:
里面的meta是空的。但是可以在matched中找到title
而且这个title是首页的。
虽然这里只有首页出现了错误,但是是因为首页是有嵌套路由的,而其他的组件没有,因此才不会出错,但要是其他的页面也有嵌套路由,那么to.meta.title就不适用了。
因此要改成无论如何都能找到的位置:to.matched[0].meta.title;
router.beforeEach((to, from, next) => {
// 从from跳转到to
// document.title = to.meta.title;
// 但是在首页中有点错误,因为路由的嵌套,所以需要:。
document.title = to.matched[0].meta.title;
console.log(to);
next()
})
meta:元数据–描述数据的数据