vuejs2 - 从 Vuex Action 和组件更改路由

标签 vuejs2 vue-router vuex

用户通过登录表单成功登录我的应用程序后。我想检查他们是否有个人资料。如果他们 我想将它们发送到新闻页面。如果他们 不要有一套,我希望它将它们重定向到“设置”页面。我将如何使用 Vuex 来做到这一点?

我想有几个选择:

1. 负责重定向的组件? (感觉不对)

登录.vue

handleFormSubmit () {
this.$store.dispatch('loginFormSubmit', formData)
    .then(() => {
      // This feels a bit gross
      this.$store.dispatch('getUserProfile')
        .then(() => this.$router.push('/news'))
        .catch(() => this.$router.push('/settings'))
    })
    .catch(() => {
      this.loginError = true
    })
}

2. 我会在行动中承担责任吗?

用户操作.js
export const getUserProfile = ({commit}) => {
  commit(types.USER_PROFILE_REQUEST)
  const options = {
    url: `${API_URL}/profile`,
    method: 'GET'
  }

  return request(options)
    .then((profileSettings) => {
      // Would I change the router to News here??

      commit(types.USER_PROFILE_SUCCESS, profileSettings)
      return Promise.resolve(profileSettings)
    })
    .catch((error) => {
      // Would I change the router to Settings here??

      commit(types.UI_MENU_HIDE)
      return Promise.reject(error)
    })
}

export const loginFormSubmit = ({dispatch, commit}, { email, password }) => {
  console.log(email, password)
  commit(types.USER_LOGIN_REQUEST)
  const options = {
    url: `${API_URL}/token`
  }
  return request(options)
    .then((response) => {
      dispatch('getUserProfile')
      commit(types.USER_LOGIN_SUCCESS, response.token)
      return Promise.resolve(response.token)
    })
    .catch((error) => {
      commit(types.USER_LOGIN_FAILURE, error)
      return Promise.reject(error)
    })
}

3. 或许应该放在带防护罩的路由器里?

登录.vue
handleFormSubmit () {
this.$store.dispatch('loginFormSubmit', formData)
    .then(() => this.$router.push('/news'))
    .catch(() => {
      this.loginError = true
    })
}

然后在我的路由器中:
const routes = [
      {
        path: 'news',
        alias: '',
        component: NewsView,
        name: 'News',
        meta: { description: 'News feed page' },
        beforeEnter: (to, from, next) => {
          store.dispatch('getUserProfile')
-          .then((resp) => {
-            // Profile set
-            next()
-          })
-          .catch(() => {
-            // No profile set
-            next({ name: 'settings' })
-          })
        }
      },
]

4. 监听 store 变化,然后改变 route
  computed: {
    isAuthenticated () {
      return this.$store.getters.isAuthenticated
    }
  },

  watch: {
    isAuthenticated () {
      this.$router.push('/calendar')
    }
  },
  methods: {
    handleSubmit (formData) {
      // Updates isAuthenticated on success
      this.$store.dispatch('requestAuthToken', formData)
    }
  }

也许三四号最好?它感觉最干净,但很想知道你们的想法:D

感谢您提前抽出时间!

最佳答案

我认为您想要一个版本的想法#2。为什么不这样:

  • 您调用handleFormSubmit()Login.vue发送loginFormSubmit()行动。也许在 Login.vue 中启用加载状态此时对于 UX。
  • 如果用户可以登录,您调用getUserProfile() , 否则在 Login.vue 中显示错误
  • getUserProfile()从 API
  • 获取
  • 你测试response从 API 在您的操作中或通过 response到一个单独的突变来做到这一点。
  • 如果用户有个人资料数据,更新 staterouter.push('/pathToNews') , 否则 router.push('/pathToSettings')

  • 这里是简化的伪代码来说明这个概念:

    // store
    
      state: {
        userProfile: {}
      },
    
      mutations: {
        setUserProfile (state, payload) {
          state.userProfile = payload
        }
      },
    
      actions: {
        getUserProfile() {
          let self = this
          axios.get('${API_URL}/token')
          .then(function (response) {
            // test response against what is expected for a populated profile
            if (response.data is a populated user profile) {
              self.commit('setUserProfile', response.data)
              self.router.push('/news')
            } else {
              self.router.push('/settings')
            }
          })
          .catch(function (error) {
            console.error(error);
            // handle your error
          })
          .finally(function () {
            // always executed
          })
        }
      }
    

    关于vuejs2 - 从 Vuex Action 和组件更改路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44801333/

    相关文章:

    javascript - 为什么分页链接点击后返回json? (Vue.js 2)

    javascript - 如何使用 Vue CLI 3 安装 vue 路由器插件?

    javascript - Vue.js 和 Firebase 'User' 信息

    javascript - 无法将 VueJS 2 哈希解析为空字符串

    vue.js - Vuex + 摩卡 : Committing mutations in tests throws warning 'Do not mutate vuex store state'

    javascript - 如何在加载某些异步数据(在 Vuex 存储中)之前防止任何路由?

    javascript - Vue 和带模板标签的条件渲染

    javascript - 如何在 VueJS 的 promise 中设置数组对象属性的值?

    vuejs2 - $router.replace() 不更新浏览器查询字符串

    javascript - 如何在填充特定值时调用 Vue.js 组件上的方法,但仅调用一次