【问题标题】:how can i use async and await in action object in vuex?如何在 vuex 的操作对象中使用异步和等待?
【发布时间】:2021-02-14 07:06:14
【问题描述】:

我将使用一个 API 并从一些信息中删除它,我在突变中使用 async/await,但正如您所知,我们在突变中使用异步数据不是标准的,我们必须在操作中使用它,但是我们如何可以吗?

这里是我的 vuex 代码:

import axios from "axios";


const state = {
    token: "hjOa0PgKqC7zm86P10F3BQkTuLsEV4wh",
    posts: [],
    pending: true,
    error: false,
}
const mutations = {
    async getDataFromApi(state) {
        try {
            const res = await axios.get(
                `https://api.nytimes.com/svc/movies/v2/reviews/picks.json?api-key=${state.token}`
            );
            if (res.status == 200) {
                state.posts = res.data;
                state.error = false;
            }
        } catch (e) {
            state.posts = null;
            state.error = e;
        }
        state.pending = false;
    },
};
const actions = {
    showData({
        commit
    }) {
        commit("getDataFromApi");
    },
}

这里是我在组件中使用的 vuejs 代码:

<script>
import { mapState } from "vuex";
export default {
  name: "Home",
  mounted() {
    this.getDataFromApi();
  },
  computed: {
    ...mapState(["pending", "error", "posts"]),
  },
  methods: {
    getDataFromApi() {
      this.$store.dispatch("showData");
    },
  },
};
</script>

它在突变中完美运行,但对于标准,如何在实际中使用它而不是突变?

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    嗯,实际上它与您目前所做的非常相似:

    const mutations = {
      getDataFromApi(state, data) {
        state.posts = data;
        state.error = false;
        state.pending = false;
      },
      setError(state, error) {
        state.error = error;
        state.posts = null;
        state.pending = false;
      },
    };
    
    const actions = {
      async showData({ commit }) {
        try {
          const res = await axios.get(
            `https://api.nytimes.com/svc/movies/v2/reviews/picks.json?api-key=${state.token}`
          );
          if (res.status == 200) {
            commit("getDataFromApi", res.data);
          } else {
            commit("setError", new Error("Something went wrong."));
          }
        } catch (e) {
          commit("setError", e);
        }
      },
    };
    

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 2021-11-01
      • 2015-10-16
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2016-03-16
      • 2018-02-23
      • 1970-01-01
      相关资源
      最近更新 更多