vue 导航守卫

导航守卫
    我们考虑一个需求:在一个spa应用中,如何给改变网页的标题呢?
    spa只有一个固定的HTML,切换不同的页面时,标题并不会变
    但是我们可以通过js来修改<title>的内容。document.title = '新标题'
    那么,在Vue项目中,在哪修改比较合适呢?

普通修改方式:在mounted函数执行相应的代码就行修改,但是当页面较多时,不容易维护

什么时导航守卫?
    vue-router提供的导航守卫主要用来监听路由的进入和离开
    vue-router提供了beforeEach和afterEach的钩子函数,它会在路由即将
        改变前和改变后触发
   

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/components/Home'
import About from '@/components/About'
import HomeNews from '@/components/HomeNews'
import HomeMes from '@/components/HomeMes'

import User from '@/components/User'

Vue.use(VueRouter)

const routes = [
  {
    path: '',
    // redirect重定向
    redirect: '/home',

  },
  {
    path: '/home',
    component: Home,
    meta: {
      title:'家园'
    },
    children: [
      {
        path: '',
        // redirect重定向
        redirect: 'news'
      },
      {
        path: 'news',
        component:HomeNews
      },
      {
        path: 'mes',
        component:HomeMes
      }
    ]
  },
  {
    path: '/about',
    component: About,
    meta: {
      title:'关于我们'
    },
    beforeEnter: (to, from, next) => {
      console.log('路由独享的守卫')
      next()
    }
  },
  {
    // 路由传值
    path: '/user/:id',
    // 懒加载 //一个懒加载路由对应一个js文件,访问路由才请求这个js文件
    component: ()=>import('../components/User'),
    // meta:元数据(描述数据的数据)
    meta: {
      title:'个人中心'
    },
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 前置钩子(hook)
router.beforeEach((to,from,next) => {
  // 从from跳转to
  // to 和 from都是route对象
  document.title = to.matched[0].meta.title
  // 调用该方法后,才能进入下一个钩子
  // 如果是后置钩子,也就是afterEach,不需要主动调用next()函数

  // 这里其实可以判断用户登陆权限之类的,拦截访问 ,权限不符调用next(false)拦截
  next()
})

// 后置钩子
router.afterEach((to,from) => {
  console.log('---')
})
export default router
原文地址:https://www.cnblogs.com/cl94/p/12364457.html