VueRouter导航守卫

1、全局拦截:router.beforeEach

import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView
  }
]
const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  console.log('to', to);
  console.log('from', from);
})
export default router

当路由进行跳转的时候,router.beforeEach就会把跳转拦截下来,只有遇到next()才会放行,to代表将要跳转的路由信息,from代表跳转前路由的信息,next代表路由放行

这是没有next()的

 这是有next()的

router.beforeEach((to, from, next) => {
  console.log('to', to);
  console.log('from', from);
  next()
})

2、局部拦截:局部拦截是写在需要拦截的路由里,以键值对的方式,表示只有跳转到该路由时,才会进行路由拦截,参数用法和全局拦截一样

import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    beforeEnter: (to, from, next) => {
      console.log('to', to);
      console.log('from', from);
    }
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView
  }
]
const router = new VueRouter({
  routes
})
export default router

3、组件内的拦截:导航守卫写在所要进行拦截的组件内部,用法与局部拦截一样,表示只拦截当前组件的路由

<template>
  <div class="home">
    <h1>home</h1>
  </div>
</template>

<script>
export default {
  name: 'home',
  beforeRouteEnter(to, from, next) {
    console.log('to', to);
    console.log('from', from);
  }
}
</script>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值