Vue - vue-router - 导航守卫


一、需求

当点击到哪个模块的时候, 就把title修改为哪个模块的名字.

二、方法一 : 使用生命周期函数

  • created() : 当组件被创建的时候回调created函数
  • mounted() : 当组件被挂载到DOM上的时候回调mounted函数
  • updated() : 当页面发生更新的时候回调updated函数
<template>
  <div>
    <h3>
      我是Home
    </h3>
    <router-link to="/home/news" tag="button">新闻</router-link>
    <router-link to="/home/message" tag="button">消息</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
  export default {
    name: 'Home',
    // 当组件被创建的时候修改title
    created() {
      document.title = '首页'
    },
  }
</script>

<style>
  .router-link-active {
    color: red;
  }
</style>

这样的做法有一个弊端, 就是每个组件都需要添加created函数, 造成代码冗余

二、方法二 : 监听全局跳转

使用 router.beforeEach() 监听全局跳转
beforeEach()函数里面接收一个函数, 函数又需要三个参数 (to, from, next), 从from跳转到to
里面必须调用next()方法, 否则将无法跳转

2.1 在路由里面添加源数据

const routes = [
  {
    path: '',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    meta: {
      title: '首页'
    },
    children: [{
      path: '',
      redirect: '/home/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: '配置'
    }
  }
]

2.2 从from跳转到to

router.beforeEach((to, from, next) => {
  // 把源数据里面的title赋值给元素的title
  document.title = to.matched[0].meta.title
  next()
})

三、导航守卫

beforeEach()也称为前置钩子 , 是全局导航守卫
除了beforeEach() 还有 afterEach() , 是全局后置钩子.

四、路由独享的守卫

可以在路由配置上直接定义 beforeEnter守卫

const routes = [
  {
    path: '/home',
    component: Home,
    meta: {
      title: '首页'
    },
    beforeEnter: (to, from, next) => {
    	// ...
    }
  }
]

五、组件内的导航守卫

5.1 beforeRouterEnter()

beforeRouterEnter(to, from, next){
	// 在渲染该组件的对应录用后被confirm前调用
	// 不能获取组件实例 this
	// 因为当守卫执行前, 组件实例还没被创建
}

5.2 beforeRouterUpdate()

beforeRouterUpdate(to, from, next){
	// 在当前路由改变, 但是该组件被复用时调用
	// 例如: 一个带有动态参数的路径, /foo/:id. 在/foo/1 和 /foo/2之间跳转的时候, 由于会渲染同样的Foo组件, 因此组件实例会被复用, 这个钩子就会在这个情况下被调用
	// 可以访问组件实例 this
}

5.1 beforeRouterLeave()

beforeRouterLeave(to, from, next){
	// 导航离开该组件的对应路由时调用
	// 可以访问组件实例 this
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值