Vue navigation guard (routing guard)

As Vue-cli project when feeling to do some verification before routing jumps, such as login verification is a universal demand site.
In this regard, beforeEach vue-router offers can be easily implemented global navigation guard (navigation-guards). The internal components of the navigation function using the same guard, but different function name (beforeRouteEnter, beforeRouteUpdate (2.2 added), beforeRouteLeave).

Official documents Address: https://router.vuejs.org/zh-cn/advanced/navigation-guards.html

How to set up a global guard

You can use router.beforeEach registered a global pre-guard: that is registered under your router configuration

const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... }) 

When a navigation triggered global front guards call in order of creation. Guard is analyzed and executed asynchronously, this time until the navigation has been in the guard resolve all finished waiting .

Each method receives three guards parameters:

  • to: Route: About to enter the target route object

  • from: Route: Was about to leave the current navigation route

  • next: Function: Be sure to call this method to resolve this hook. Implementation of the results depend on nextthe call parameters method.

    • next(): The next hook pipeline. If all the hook either finished, the status of navigation is Confirmed (confirmation).

    • next(false): Interrupt the current navigation. If the browser's URL has changed (manually by the user or may be the browser back button), the URL address will be reset to the fromaddress corresponding to the route.

    • next('/')Ornext({ path: '/' }) : Go to a different address. The current navigation is interrupted, then a new navigation. You can to nextpass an arbitrary position of the object, and allows setting such as replace: true, name: 'home'options and the like for use in any of router-linkthe toprop or router.pushthe options.

    • next(error): (2.4.0+) if the incoming nextparameter is an Errorinstance, the navigation will be terminated and the error will be passed to the router.onError()registered callbacks.

Make sure to call the nextmethod, otherwise the hook will not be resolved.

A simple and practical small example:

const router = new VueRouter({ ... }) //这是路由配置,我就不多说了 const whiteList = ['/error', '/register/regindex', '/register/userauthent', '/register/submit'] // 路由白名单 vueRouter.beforeEach(function(to,from,next){ console.log("进入守卫"); if (userInfo.user_id>0){ console.log("登录成功"); next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的; }else{ console.log("登录失败"); getUserInfo.then(res => { if(res){ if (res.user_id){ if (res.status == 4) { //账号冻结 next({ path: '/error', replace: true, query: { noGoBack: true } }) } if (res.status == 3) { //认证审核中 next({ path: '/register/submit', replace: true, query: { noGoBack: true } }) } if (res.status != 1 && res.status != 3) { if (!res.mobile ) { next({ path: '/register/regindex', replace: true, query: { noGoBack: true }}) } else { //绑定完手机号了 next({ path: '/register/userauthent', replace: true, query: { noGoBack: true } }) } } next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的; }else{ if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入 next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的; }else{ next({ path: '/register/regindex', replace: true, query: { noGoBack: true }}) } } }else{ } } }).catch(()=>{ //跳转失败页面 next({ path: '/error', replace: true, query: { noGoBack: true }}) }) } }); export default router 

Tips: some places vuex involved in the transfer of methods and data to judge, but the reason is not because the examples show, only to provide ideas for your reference.

Finally, and everyone said that if too many whitelist or more projects, we need to whitelist replaced vue-router route meta information:

meta field (metadata)

When routing configuration, routing added directly to each custom object meta, meta object may be provided in some of the state, to do something. Use it for logon check very appropriate

{
  path: '/actile',
  name: 'Actile',
  component: Actile,
  meta: {
    login_require: false
  },
},
{
  path: '/goodslist',
  name: 'goodslist',
  component: Goodslist,
  meta: {
    login_require: true
  },
  children:[
    {
      path: 'online',
      component: GoodslistOnline
    }
  ]
}

Here we only need to determine the following item meta object login_require is not true, you can do some limits

router.beforeEach((to, from, next) => { if (to.matched.some(function (item) { return item.meta.login_require })) { next('/login') } else next() })


 

 

 

 

 

.

Guess you like

Origin www.cnblogs.com/jianxian/p/12079485.html