码迷,mamicode.com
首页 > 其他好文 > 详细

vue导航守卫

时间:2018-07-30 21:43:30      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:eth   pre   lse   create   data   template   span   cti   style   

三部分

  1. router(VueRouter实例)守卫 -- 全局路由守卫
  2. router守卫 -- 路由守卫
  3. component守卫 -- 组件守卫

  • const router = new Router({})
  • router.beforeEach(function (to,from,next) {} //
  • export default router
    router.beforeEach(function (to,from,next) {
      // console.log(to,from)
      if(to.name == ‘blog‘) {
        if(to.matched[0].meta.is_login) {
          next()
        }else{
          console.log("login")
          next({name: ‘login‘})
        }
      }else if(to.name == ‘login‘) {
        if(to.matched[0].meta.is_login) {
          next({name: from.name})
          console.log(from)
        }else {
          next()
        }
      }else {
        next()
      }
    })
    <template>
        <button @click=‘login‘>LOGIN</button>
    </template>
    <script>
    export default {
        created() {
            // console.log(this.$route)
        },
        methods: {
            login() {
                // console.log(this.$route)
                this.$route.matched[0].meta.is_login = true;  //
                this.$router.push({name: ‘blog‘})  //
            }
        }
    }
    </script>

 


Vue.use(Router)

const router =  new Router({
  routes: [
    {
      path: ‘/login‘,
      name: ‘login‘,
      component: Login,
      meta: {
        index: 3,
        is_login: true
      },
      beforeEnter(to,from,next) {
        // console.log(to,from)
        if(to.meta.is_login) {
          next({name:from.name})
        }else{
          next()
        }
      }
    }
  ]
})

router.beforeEach(function (to,from,next) {
  // console.log(to)
  if(to.name == ‘blog‘) {
    if(to.matched[0].meta.is_login) {
      next()
    }else{
      // console.log("login")
      next({name: ‘login‘})
    }
  }else if(to.name == ‘login‘) {
    if(to.matched[0].meta.is_login) {
      next({name: from.name})
      // console.log(from)
    }else {
      next()
    }
  }else {
    next()
  }
})

export default router

3.

未完待续


vue导航守卫

标签:eth   pre   lse   create   data   template   span   cti   style   

原文地址:https://www.cnblogs.com/goff-mi/p/9392402.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!