我使用 vuex 和 laravel 作为我的项目的后端。
登录后重定向不起作用。这是我的代码:
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()
}
)
如何自动重定向?
感谢您的帮助
最佳答案
我认为导航的副作用不应该成为 Vuex 存储操作的一部分,除非您 100% 确定它始终需要作为此操作的一部分发生。无论您在应用程序的哪个位置执行此操作,都应该处理该导航。要实现这一点,您需要做两件事
在你的操作中,返回 Vue.http 的 promise
在您调用它的组件中使用 .then 处理成功
//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)
}
}
关于api - Vuex 和路由 - 登录后重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42562131/