首页 文章

从Vuex行动中回复承诺

提问于
浏览
58

我最近开始将事物从jQ迁移到更结构化的框架VueJS,我喜欢它!

从概念上讲,Vuex对我来说已经是一个典型的转变,但我相信我现在知道它的全部内容,完全得到它!但是存在一些小的灰色区域,主要是从实施的角度来看 .

我觉得这个设计很好,但不知道它是否与单向数据流的Vuex相矛盾 .

基本上,从动作中返回一个promise(类似)对象被认为是一种好习惯吗?我将它们视为异步包装器,具有失败状态等,因此似乎非常适合返回一个承诺 . 相反,mutators只是改变了一些东西,而且是商店/模块中的纯粹结构 .

3 回答

  • 5

    Vuex中的 actions 是异步的 . 允许调用函数(操作的发起者)知道操作完成的唯一方法是返回Promise并稍后解析它 .

    下面是一个示例: myAction 返回 Promise ,进行http调用并稍后解析或拒绝 Promise - 所有异步

    actions: {
        myAction(context, data) {
            return new Promise((resolve, reject) => {
                // Do something here... lets say, a http call using vue-resource
                this.$http("/api/something").then(response => {
                    // http success, call the mutator and change something in state
                    resolve(response);  // Let the calling function know that http is done. You may send some data back
                }, error => {
                    // http failed, let the calling function know that action did not work out
                    reject(error);
                })
            })
        }
    }
    

    现在,当您的Vue组件启动 myAction 时,它将获取此Promise对象并可以知道它是否成功 . 以下是Vue组件的一些示例代码:

    export default {
        mounted: function() {
            // This component just got created. Lets fetch some data here using an action
            this.$store.dispatch("myAction").then(response => {
                console.log("Got some data, now lets show something in this component")
            }, error => {
                console.error("Got nothing from server. Prompt user to check internet connection and try again")
            })
        }
    }
    

    如您所见, actions 返回 Promise 非常有用 . 否则,动作发起者无法知道发生了什么以及何时足够稳定以在用户界面上显示某些内容 .

    关于 mutators 的最后一个注释 - 正如你正确指出的那样,它们是同步的 . 它们改变 state 中的内容,通常从 actions 调用 . 没有必要将 Promisesmutators 混合,因为 actions 处理该部分 .

    Edit: My views on the Vuex cycle of uni-directional data flow:

    如果在组件中访问类似 this.$store.state["your data key"] 的数据,则数据流是单向的 .

    行动的承诺只是让组件知道行动是完整的 .

    组件可以从上面示例中的promise promise函数中获取数据(不是单向的,因此不推荐),也可以直接来自 $store.state["your data key"] ,它是单向的并遵循vuex数据生命周期 .

    一旦在您的操作中完成http调用,上面的段落假定您的mutator使用 Vue.set(state, "your data key", http_data) .

  • 132

    仅供参考有关封闭主题的信息: you don’t have to create a promise, axios returns one itself:

    参考:https://forum.vuejs.org/t/how-to-resolve-a-promise-object-in-a-vuex-action-and-redirect-to-another-route/18254/4

    例:

    export const loginForm = ({commit},data) => {
            return axios.post('http://localhost:8000/api/login',data).then((response) => {
                console.log(response);
                commit('logUserIn',response.data.data);
            }).catch((error) => {
                commit('unAuthorisedUser',{
                    error:error.response.data
                })
            })
    };
    
  • 0

    Actions

    ADD_PRODUCT : (context,product) => {
      return Axios.post(uri, product).then((response) => {
        if (response.status === 'success') {  
          context.commit('SET_PRODUCT',response.data.data)
        }
        return response.data
      });
    });
    

    Component

    this.$store.dispatch('ADD_PRODUCT',data).then((res) => {
      if (res.status === 'success') {
        // write your success actions here....
      } else {
         // write your error actions here...
      }
    })
    

相关问题