簡體   English   中英

VueRouter等待ajax完成

[英]VueRouter wait for ajax is done

我正在構建SPA,問題是檢查用戶是否為管理員。

Vue.auth.getUserInfo()我想停止整個應用程序並等待API響應, Vue.auth.user.isAdmin始終為false,因為我沒有來自api的響應...

這是router.beforeEach

router.beforeEach((to, from, next) => {

   if(Vue.auth.user.authenticated == false) {
       Vue.auth.getUserInfo();
   }

   if(Vue.auth.user.isAdmin) {
      next({ name: 'admin.index' })
   } else {
      next({name: 'client.index'})
   }
}

獲取用戶信息的方法:

getUserInfo() {
    Vue.http.get('/api/me')
        .then(({data}) => {
            this.user = data;
        }, () => {
            this.logout();
        })
}

這是異步請求。

您別無選擇。 1.將此功能移至vue-router並放置您的代碼:

   if(Vue.auth.user.authenticated == false) {
       Vue.auth.getUserInfo();
   }

   if(Vue.auth.user.isAdmin) {
      next({ name: 'admin.index' })
   } else {
      next({name: 'client.index'})
   }
}

在您的請求的then()函數中。

  1. 可能對您的學習曲線更好-將getUserInfo()修改為基於承諾。

然后,您的auth模塊中將包含以下內容:

var getUserInfo = new Promise((resolve,reject) => {
 Vue.http.get('/api/me')
        .then(({data}) => {
            this.user = data;
            resolve();
        }, () => {
            this.logout()
            reject();
        })
}

在您的路由器中:

router.beforeEach((to, from, next) => {

   if(Vue.auth.user.authenticated == false) {
       Vue.auth.getUserInfo().then(()=>{
if(Vue.auth.user.isAdmin) {
      next({ name: 'admin.index' })
   } else {
      next({name: 'client.index'})
   }
});
   }


}

我沒有編輯器,因此可能有一些小問題,但通常應該可以。 希望能幫助到你!

假設在您的Vue.auth.getUserInfo()邏輯中管理Vue.auth.user.isAdmin的狀態,則可以嘗試一種Vue.auth.getUserInfo()方法(未試用):

getUserInfo() {
  return new Promise((resolve, reject) => {
    Vue.http.get('/api/me')
      .then(({data}) => {
        this.user = data;
        // Or, to use when consuming this within the then() method:
        resolve(data);
      }, () => {
        reject();
      })
  })
}

然后,當您在警衛人員中使用它時( https://router.vuejs.org/en/advanced/navigation-guards.html ):

// A couple small auth/guard helper functions
function guardCheck(next) {
  if(Vue.auth.user.isAdmin) {
    next({ name: 'admin.index' })
  } else {
    next({name: 'client.index'})
  }
}
function guardLogout(next) {
  Vue.auth.user.logout()
    .then(() => {
      next({ name: 'home.index', params: { logout: success }})
    })
}

router.beforeEach((to, from, next) => {
  if(Vue.auth.user.authenticated === false && !to.matched.some(record => record.meta.isGuest)) {
    Vue.auth.getUserInfo()
      .then((user) => {
        guardCheck(next)
      })
      .catch(() => {
        // Not sure how your logout logic works but maybe...
        guardLogout(next)
      })
  } else {
     guardCheck(next)
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM