2017-08-24 140 views
6

在我的應用程序的一些途徑只是通過驗證的用戶訪問重定向到請求的頁面登錄後。
當一個未經驗證的用戶點擊一個鏈接,爲此他必須簽署,他將被重定向到登錄組件。

如果用戶成功登錄,我想他重定向到之前,他必須進行登錄他請求的URL。然而,也應該有一個默認路由,萬一他在登錄之前用戶沒有請求另一個URL。

我怎樣才能做到這一點使用VUE路由器?
使用VUE路由器


我不重定向代碼登錄後

router.beforeEach(
    (to, from, next) => { 
     if(to.matched.some(record => record.meta.forVisitors)) { 
      next() 
     } else if(to.matched.some(record => record.meta.forAuth)) { 
      if(!Vue.auth.isAuthenticated()) { 
       next({ 
        path: '/login' 
        // Redirect to original path if specified 
       }) 
      } else { 
       next() 
      } 
     } else { 
      next() 
     } 
    }   
) 



在我登錄組件我的登錄功能

login() { 
    var data = { 
     client_id: 2, 
     client_secret: '**************', 
     grant_type: 'password', 
     username: this.email, 
     password: this.password 
    } 
    // send data 
    this.$http.post('oauth/token', data) 
     .then(response => { 
      // authenticate the user 
      this.$auth.setToken(response.body.access_token, 
      response.body.expires_in + Date.now()) 
      // redirect to route after successful login 
      this.$router.push('/') 
      }) 



我將是任何形式的非常感謝幫幫我!

+13

你可以做類似'下一個({路徑:「?/登錄從=」 + to.path})',然後你的登錄頁面上檢查'from'查詢參數設置,並做了重定向 –

+0

@ FlorianHaider這聽起來像是一個很好的解決方案!如何檢查從我的登錄組件設置的查詢參數? – Schwesi

+3

@Schwesi你使用'this。$ route.query.from'獲得查詢參數。如果沒有查詢出現,你會得到一個空物體 –

回答

2

在有點不同的方式,這可以通過在你的路徑添加查詢參數時要重定向,然後當你登錄,如果參數是設置檢查來實現;如果已設置,則使用它或以其他方式在根目錄上回退。

在代碼應該是這個樣子:

把一個行動,你的鏈接,例如:

onLinkClicked() { 
    if(!isAuthenticated) { 
    // If not authenticated, add a path where to redirect after login. 
    this.$router.push({ name: 'login', query: { redirect: '/path' } }); 
    } 
} 

登錄提交操作

submitForm() { 
    AuthService.login(this.credentials) 
    .then(() => this.$router.push(this.$route.query.redirect || '/')) 
    .catch(error => { /*handle errors*/ }) 
} 

希望它幫助。