bilibili学习之改变跳转的title实现方式

官方链接:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html

导航守卫:

vue-router提供的导航守卫主要用来监听路由的进入和离开的。

vue-router提供了beforeEach和afterEach的钩子函数,他们会在路由即将改变前和改变后触发

利用生命周期函数created()

在每个VUE文件中添加以下代码

created(){
			console.log('created');
			document.title = '用户'
		},

可实现跳转之后的title的改变,效果图:

 方式2:

在每个路由的配置中,添加meta(元数据),添加title,

{
		path:'/about',
		component:About,
		meta:{
			title:'关于'
		}
	},

然后调用:

next()必须调用,否则会出错

//to;即将要进入的目标的路由对象
//from:当前导航即将要离开的路由对象
//next:调用该方法后,才能进入下一个钩子

router.beforeEach((to,from,next) =>{
	 //从from跳到to
	 document.title = to.matched[0].meta.title
	 next()
 })

全局代码为:

//配置路由相关的信息
import Vue from 'vue'
import VueRouter from 'vue-router'
// import Home from '../components/Home.vue'
// import About from '../components/About.vue'
// import User from '../components/user.vue'

const Home = () => import('../components/Home.vue')
const HomeNews = () => import('../components/HomeNews.vue')
const HomeMessage = () => import('../components/HomeMessage.vue')
const About = () => import('../components/About.vue') 
const User = () => import('../components/user.vue')
const Profile = () => import('../components/Profile.vue')
//1.通过Vue.use(插件),安装插件(要想使用vue.use,必须先import)
Vue.use(VueRouter)
//2.创建VueRouter对象,并且传入路由映射配置
//一个映射关系就是一个对象
const routes = [
	{
		path:'',
		redirect:'/home' 
	},
	{
		path:'/home',
		component:Home,
		meta:{
			title:'首页'
		},
		children:[
			{
				path:'',
				redirect:'news'
			},
			{
				path:'news',
				component:HomeNews
			},
			{
				path:'message',
				component:HomeMessage
			}
		]
	},
	{
		path:'/about',
		component:About,
		meta:{
			title:'关于'
		}
	},
	{
		path:'/user/:userId',
		component:User,
		meta:{
			title:'用户'
		}
	},
	{
		path:'/profile',
		component:Profile,
		meta:{
			title:'档案'
		}
	}
]
const router = new VueRouter({
	//配置路径 和组件之间的映射关系
	routes,
	mode:'history',//将路由地址#去掉,将默认的哈希模式改成HTML5的history形式  
	linkActiveClass:'active'//修改router-link的默认名称
})

 router.beforeEach((to,from,next) =>{
	 //从from跳到to
	 document.title = to.matched[0].meta.title
	 next()
 })


//3 将router对象传入到vue实例中
export default router//(将router导出,在main.js导入)

补充:

后置钩子,afterEach,不需要主动调用next()函数

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值