鍍金池/ 問答/HTML/ vue通過beforeEach從首頁跳轉(zhuǎn)到注冊頁面后,點擊返回會再次進(jìn)入首頁?

vue通過beforeEach從首頁跳轉(zhuǎn)到注冊頁面后,點擊返回會再次進(jìn)入首頁?

需求是進(jìn)入首頁,通過uid判斷是否用戶為會員,如果不是會員,則跳轉(zhuǎn)到注冊頁面,但是有個問題就是跳轉(zhuǎn)到注冊頁面后點擊返回按鈕,就會跳轉(zhuǎn)到上一頁面也就是首頁(然后由于不是會員就停留在了注冊頁),按邏輯頁也應(yīng)該是無限循環(huán)啊,實際上,我要點擊兩次返回按鈕才能退出注冊頁。困擾我多時,往有人能幫解答,不勝感激!

進(jìn)入首頁memberCenter后,輸出
to memberCenter
to register

第一次點擊返回按鈕,輸出,并停留在注冊頁面
to memberCenter

第二次點擊返回按鈕,退出注冊頁面(即退出微信公眾號,但跟微信無關(guān),其他瀏覽器也有這個問題)

代碼

router.beforeEach(async (to, from, next) => {
  console.log('to', to.name);
  Indicator.open('努力加載中...');

  // 注冊時進(jìn)入會員中心會請求會員中心接口,注冊后需要更新會員中心接口
  if (to.path === '/memberCenter') {
    // 會員中心數(shù)據(jù)為空
    if (!store.state.memberCenterData) {
      await store.dispatch('getMemberCenterAction');
    }

    Vue.prototype.$nextTick(() => {
      Indicator.close();
    });

    if (store.state.memberCenterData.uid) {
      next({
        path: '/register',
      });
      return;
    }
  }
  next();
});

補(bǔ)充:
另外在首頁(也就是會員中心)通過beforeRouteEnter里的next({name: 'register'})跳轉(zhuǎn)到注冊頁,在注冊點擊返回也會返回到上一頁,好像全局的beforeEach和組件的beforeRouteEnter里的next()作用都變成了router.push(),而我想要是類似router.replace()的效果

回答
編輯回答
尤禮

沒遇到過需要點擊兩次才能到首頁的情況。
不過要實現(xiàn)需要還是容易的,只要判斷是注冊頁到主頁的跳轉(zhuǎn)就直接next(),這滿足你的需求。

  if (to.path === '/memberCenter') {
    // 會員中心數(shù)據(jù)為空
    if(from.path==='/register'){
      next();
      return;
     }else{
     ...
     }
  }

你這鉤子是不會無限跳轉(zhuǎn)的,因為你沒有寫to.name=='/register'的鉤子

2018年3月30日 22:34