2017-03-02 168 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