Vue.js: Nuxt error handling

时光毁灭记忆、已成空白 提交于 2019-12-03 10:05:55

Use Promise in action

Example in vuex:

NEW_AUTH({ commit }) {
    return new Promise((resolve, reject) => {
      this.$axios.$get('/token').then((res) => {
        ...
        resolve();
      }).catch((error) => {
        reject(error);
      })
    })
  }

In page:

this.$store.dispatch('NEW_AUTH')
   .then(() => ... )
   .catch((error) => ... )

To address the Con from Alternative 2 you can either

(a) pass in the name of the component or even a reference to the component or

(b) you can persist the error in the state for the component that made the call. Then in your component you could check if there is an error and display it. For that you could use a mixin to forgo the need for boiler plate.,

in store/auth.js:

export const actions = {
    login({ commit }, { email, password }) {
        return this.$axios.post('/api/login', {
            email,
            password,
        }).then((res) => {
            doSomething(res);
            commit('save_to_state', { response: res });
        }).catch((error) => {
            commit('save_to_state', { error });
        });
    },
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!