【问题标题】:VUEX Response of Dispatch VUE调度 VUE 的 VUEX 响应
【发布时间】:2021-05-04 04:31:46
【问题描述】:

如何从另一个组件捕获 vuex 调度的响应?因此,例如,如果响应是 200,我会做其他事情。 组件.vue

this.$store.dispatch("setTrigger");

store.js


    setTrigger({ state }) {
      axios
        .post(
          "https://xxx.us/api/savetriggers",
          {
            organizationsDefaultTriggerTime: state.organizationsDefaultTriggerTime,
            runFailedDefaultTriggerTime: state.runFailedDefaultTriggerTime,
          },
          {
            headers: {
              Authorization: `Bearer ${state.currentAuthToken}`,
            },
          }
        )
        .then((response) => {
          console.log(response.data);
        })
        .catch((error) => {
          console.log(error.data);
        });
    },

setTrigger 在 store.js 中,我从组件中调用 dispatch。

我也应该使用状态和吸气剂吗?这是最佳做法吗?

【问题讨论】:

    标签: vue.js vuex response


    【解决方案1】:

    您需要从行动中转发承诺。有点像这样:

    main.js(商店)

    import Vue from "vue";
    import App from "./App.vue";
    import Vuex from "vuex";
    
    Vue.config.productionTip = false;
    
    Vue.use(Vuex);
    
    const store = new Vuex.Store({
      state: {
        something: 0
      },
      getters: {
        getSomething: (state) => state.something
      },
      actions: {
        doSomethingAction: async ({ getters }) => {
          return await new Promise((resolve) => {
            // we return the promise to resolve it inside the component
            setTimeout(() => {
              return resolve(getters.getSomething);
            }, 1000);
          });
        }
      },
      mutations: {
        updateSomething(state) {
          state.something = 1;
        }
      }
    });
    
    new Vue({
      store,
      render: (h) => h(App)
    }).$mount("#app");
    
    

    你的组件

    <template>
      <div id="app">
        <button @click="doSomethingInsideComponent">Do Something</button>
        {{ getSomething }}
      </div>
    </template>
    
    <script>
    import { mapActions, mapGetters, mapMutations } from "vuex";
    
    export default {
      name: "App",
      computed: {
        ...mapGetters(["getSomething"]), //<--- get a state from store
      },
      methods: {
        ...mapActions(["doSomethingAction"]), // <--- use dispatch froms store
        ...mapMutations(["updateSomething"]), // <-- use mutation from store
        async doSomethingInsideComponent() {
          // <-- component trigger for the promise forward
          await this.doSomethingAction().then(() => {
            // HERE YOU DO SOMETHING AFTER THE DISPTACH IS FULLFILLED...
            this.updateSomething();
          });
        },
      },
    };
    </script>
    
    <style>
    #app {
      font-family: "Avenir", Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    </style>
    

    我希望我的 cmets 解释得足够清楚。如果没有,请告诉我。 这是一个工作示例CodeSandbox


    更新

        async setTrigger({ state }) { //<-------- set this function to "async"
         return await axios //<------------ return your axios call here, and await 
            .post(
              "https://xxx.us/api/savetriggers",
              {
                organizationsDefaultTriggerTime: state.organizationsDefaultTriggerTime,
                runFailedDefaultTriggerTime: state.runFailedDefaultTriggerTime,
              },
              {
                headers: {
                  Authorization: `Bearer ${state.currentAuthToken}`,
                },
              }
            )
            .then((response) => {
              console.log(response.data);
              return response //<--------- return the response here
            })
            .catch((error) => {
              console.log(error.data);
            });
        },
    
    

    在您的组件内部,您可以使用then chaining 处理响应

    这样做是为了达到这个目的:

    this.$store.dispatch("setTrigger").then((response) => {
      // do what you want here because the store dispatch is forwarded to here
      console.log(response)
    });
    

    旁注

    你真的应该了解更多关于Promises - Javascript

    【讨论】:

    • 嗨,Deniz..非常感谢您的努力。我还是个初学者。所以这有点令人困惑。我将编辑我的问题以包含我的 store.js。如果您能告诉我如何应用它,将不胜感激!
    • 不知道如何感谢您。将在少数情况下应用它并更新您。再次感谢
    • return await axios(...) 是多余的,只是return axios(...)
    • 我和你一样开始,我很高兴有人以同样的方式帮助我。我只是偿还我的账单:) 一切都很好,兄弟
    • 您可以自己更新它。他告诉你这是为了分享它而不是与你疯狂编辑可能甚至没有注意到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2021-11-04
    • 2020-04-02
    • 2016-08-10
    • 2021-05-06
    • 2017-11-02
    • 1970-01-01
    相关资源
    最近更新 更多