2017-03-02 166 views
2

我使用vuex和laravel作爲我項目的後端。
登錄後重定向不起作用。這裏是我的代碼:
Vuex和路由 - 登錄後重定向

methods: { 
    submit() { 
     this.$validator.validateAll() 
     if (!this.errors.any()) { 
     this.$store.dispatch('SIGNIN', this.user) 
     this.$router.push({name: 'chat'}) 
     } 
    } 
} 


對於Vuex:

actions: { 
    SIGNIN (context, user) { 
     context.commit('handleLoader') 
     Vue.http.post(apiDomain + signInUrl, user, {headers: getHeaders}) 
     .then(response => { 
     if (response.status === 200) { 
      Vue.auth.setToken(response.body.token) 
      Vue.auth.setAuth(response.body.user) 
      context.commit('handleLoader') 
      // context.commit('navigateAfterSignIn') 
     } 
     }) 
    } 
} 

我的突變

mutations: { 
    signin (state) { 
     state.isLoggedIn = true 
    } 
    } 


我的路線:

export default new Router({ 
    routes: [ 
    { 
     path: '/', 
     name: 'chat', 
     component: Chat, 
     meta: { 
     forAuth: true 
     } 
    }, 
    { 
     path: '/signin', 
     name: 'signin', 
     component: Signin, 
     meta: { 
     forVisitors: true 
     } 
    }, 
    { 
     path: '/signup', 
     name: 'signup', 
     component: Signup, 
     meta: { 
     forVisitors: true 
     } 
    } 
    ], 
    mode: 'history' 
}) 

而且我對路線的保護檢查

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

如何自動重定向?
感謝您的幫助

+0

如果是,那麼你是否使用'vueRouter'然後你可以把你的'router.js'文件? –

+0

我編輯過這個職位 – Beni

+0

但是你的問題沒有**編輯**標籤,你確定嗎? –

回答

2

我不認爲導航的副作用應該是Vuex店行動的一部分,除非你是100%肯定它總是需要發生,因爲該行動的一部分。無論您在應用程序中做什麼,都應該關注該導航。要做到這一點,你需要做兩件事情

在你的行動,返回是Vue.http事情

手柄成功在你被調用此組件一個。然後從

//Store action, note Vue.http.post MUST return a thenable (Promise) 
SIGNIN (context, user) { 
    context.commit('handleLoader') 
    return Vue.http.post(apiDomain + signInUrl, user, {headers: getHeaders}) 
    .then(response => { 
     handleSettingToken(response) 
     return response 
    }) 
    } 
} 

//Component 

methods: { 
    handleLogin() { 
    return store.dispatch(SIGNIN, user) 
     .then(response => doNavigationHere(response) 
    } 
} 
承諾
+0

沒有工作:(不幸的是 – Beni

+0

它的工作:)我已經使用'承諾'。這是鏈接 http://stackoverflow.com/questions/40390411/vuex-2-0-dispatch-versus-commit – Beni