api - Vuex 和路由 - 登录后重定向

标签 api vue.js laravel-5.3 restful-url vuejs2

我使用 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/

相关文章:

api - 我可以使用 Monkeyrunner 来测试我自己的 API 吗?

javascript - 在reactjs中创建2个对象之间的关系(OnetToMany)

javascript - 旧版浏览器中的 Vue.js 条件渲染

vue.js - 如何在 Vue 组件中@extend 外部 CSS 类?

laravel - 如何在迁移 laravel 上使用 alter table 添加字段?

api - 如何将切片器值设置为Power BI中第一个可用值表单表?

javascript - 具有 REST API 架构的单页应用程序

Laravel 5.3 在路由文件 web.php 中获取请求值

javascript - 对于来自 Vue.js 和 Vuetify.js 中函数的表中的数据

php - Laravel Eloquent 联合查询