Vuex和路由 - 登录后重定向

时间:2017-03-02 17:32:56

标签: 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()
  }
)

如何自动重定向?
谢谢你的帮助

1 个答案:

答案 0 :(得分:2)

我不认为导航的副作用应该是Vuex商店行动的一部分,除非您100%确定它始终需要作为此操作的一部分发生。无论您在应用程序中执行此操作,都应该处理该导航。要做到这一点,你需要做两件事

在您的操作中,返回作为Vue.http事物的承诺

使用.then从

调用此组件中处理成功
foreach($new_array["16"]["Oct"]["DS950"] as $key=>$value){
    echo "$key = $value<br>";
}