Vuex:如果没有数据处于状态,则获取程序将分派操作

时间:2020-10-27 14:15:31

标签: vuex

我将vuex用于状态以及获取数据并将其显示在应用程序中。 但是我想知道我是否做对了。目前,我从组件fetchDataAsync钩子派发了一个mounted动作,我有一个吸气剂来显示我的数据。以下是我目前的操作方式的代码示例。

我想知道是否有必要。我真正想要的是一个吸气剂,它可以查看状态,检查数据是否已经存在,如果数据不存在,则可以调度操作以获取丢失的数据。

vuex的API不允许这样做,因此我需要在组件中添加更多逻辑。例如。如果数据取决于道具,那么我需要一个观察者来查看道具并调度fetchDataAsync动作。 对我来说,这感觉很不对,我想知道是否有更好的方法。

let store = new Vuex.Store({
  state: {
    posts: {}
  },
  mutations: {
    addPost(state, post) {
      Vue.set(state.posts, post.id, post);
    }
  },
  actions: {
    fetchPostAsync({ commit }, parameter) {
      setTimeout(
        () =>
          commit("addPost", { id: parameter, message: "got loaded asynchronous" }),
        1000
      );
    }
  },
  getters: {
    // is it somehow possible to detect: ob boy, I don't have this id,
    // I'd better dispatch an action trying to fetch it...?
    getPostById: (state) => (id) => state.posts[id]
  }
});

new Vue({
  el: "#app",
  store,
  template : "<div>{{ postToDisplay ? postToDisplay.message : 'loading...' }} </div>",
  data() {
    return {
      parameter: "a"
    };
  },
  computed: {
    ...Vuex.mapGetters(["getPostById"]),
    postToDisplay() {
      return this.getPostById(this.parameter);
    }
  },
  methods: {
    ...Vuex.mapActions(["fetchPostAsync"])
  },
  mounted() {
    this.fetchPostAsync(this.parameter);
  }
});

我还创建了一个codepen

1 个答案:

答案 0 :(得分:1)

我个人认为,您建议的解决方案(最好的解决方案是添加一个观察者,如果未找到该帖子,则派遣fetchPostAsync)。正如另一位评论者所说,吸气剂不应有副作用。