前端学习

Vue-router-导航守卫(九)

2020-05-10  本文已影响0人  小二哥很二

一、全局守卫

1、全局守卫顾名思义,是定义全局的。守卫的作用之一就是在路由来回切换的时候,浏览器的title也随之变化
index.js 配置全局导航守卫

// 全局导航守卫
// 前置守卫beforeEach(hook)
router.beforeEach((to, from, next) =>{
  // 从from跳转到to
  document.title = to.matched[0].meta.title;
  console.log(to);  // 会发现meta.title在matched[0]里面
  console.log('+++++');
  // next函数必须调用,否则报错,里面可以传参,传入路由路径也可以
  next()
});

// 后置钩子afterEach,不需要调用next
router.afterEach((to, from) => {
  console.log('-----');
})
全局导航守卫

二、路由独享守卫

1、路由独享守卫是设置路由映射里的
index.js 配置路由独享守卫

// 配置路由映射关系,一个映射关系对应一个对象
  const routes = [
  {
    path: '',
    // redirect重定向,设置默认导航栏
    redirect: '/home'
  },
  {
    path: '/user/:userId',
    component:User,
    // meta供title跳转用
    meta:{
      title:'用户'
    },
    // 路由独享守卫,顾名思义写在路由映射里的,详细可以查官网
    beforeEnter:(to, from, next) =>{
      console.log('user beforeEnter');
      next();
    }
  }

三、组件守卫

1、在Vue生命周期里,我们切换路由,都会有个created和destroyed的过程,我们不想每次切换都创建,节省性能。并且切换回来的时候仍是上一次操作选中
Home.vue

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
<!--    配置子组件路由的router-link-->
    <router-link to="/home/news" tag="button">新闻</router-link>
    <router-link to="/home/message" tag="button">消息</router-link>

    <router-view/>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',
  components: {
    HelloWorld
  },
  data(){
    return {
      path:'/home/news'
    }
  },
  // vue实例和组件 生命周期里的其中一个函数created ==>当组件被创建,就回调created
  created() {
    console.log('created-home');
    // 此时可以设置当点击某个导航栏时候,浏览器title也更改
    // document.title = '首页'
  },
  // 由于index.js映射里,home下没设置默认子映射,所以这里加个activated使其选择默认组件显示
  activated() {
    this.$router.push(this.path)
  },
  // 在离开Home路由之前,记录路由地址,在返回的时候,就默认显示上次操作的路由拉~~~
  beforeRouteLeave (to, from, next) {
    console.log(this.$route.path);
    this.path = this.$route.path;
    next();
  }
  // 当点击其它路由的时候,该组件被销毁,回调destroyed函数,默认会执行销毁生命周期
  // destroyed() {
  //   console.log('destroyed');
  // }
}
</script>

2、keep-alive属性:里面有两个属性,一个include,一个exclude,后面接路由的name
App.vue配置

<!-- keep-alive的作用是当路由之间相互切换,切换回来的时候还是保持上次的操作,
    也就是不执行destroy。它对组件进行缓存,节省性能-->
    <!-- keep-alive里加上include=“User”,代表只有路由User.vue会被缓存;相反exclude-->
    <keep-alive exclude="Profile">
      <router-view/>
    </keep-alive>
上一篇 下一篇

猜你喜欢

热点阅读