vue路由独享守卫beforeEnter

Posted on 2019-04-15 01:02  猫头唔食鱼  阅读(11818)  评论(0编辑  收藏  举报

在某个路由中,使用beforeEnter()方法,参数是to,from,next

和全局路由守卫的用法是一样的

例子:

import Vue from 'vue'
import Router from 'vue-router'
 
Vue.use(Router)
import Home from '../../view/Home.vue'
import Test from '../../view/Test.vue'
import News from '../../view/News.vue'
export default new Router({
  routes: [
    {
      name:"Home",
      path:"/",
      component:Home,
    },
    {
      name:"Test",
      path:"/test",
      component:Test,
      beforeEnter(to,from,next){
        if(to.path==="/test"){
          alert("请登录");
          next(false); // 禁止跳转
        }else{
          next()
        }
      }
    },
    {
      name:"News",
      path:"/news",
      component:News
    },
    {
      redirect:"/",
      path:"*",
    }
  ],
  mode:"history"
})