我有一个使用NuxtJS和无头Wordpress CMS建立的投资组合网站。在几个页面上,我导入了一个如下所示的mixin:
import { mapActions, mapState } from 'vuex';
export default {
  computed: {
    ...mapState({
      galleries: state => state.portfolio.galleries[0],
    })
  },
  methods: {
    ...mapActions('portfolio', ['fetchGalleries']),
  },
  async fetch() {
    await this.fetchGalleries();
  }
}Vuex模块如下所示:
export const state = () => ({
  galleries: [],
});
export const actions = {
  async fetchGalleries({ commit }) {
    let res = await this.$axios.$get(`${process.env.WP_API_URL}/wp/v2/media`);
    const data = res.reduce((acc, item) => {
      const { slug } = item.acf.category;
      (acc[slug] || (acc[slug] = [])).push(item);
      return acc;
    }, {});
    commit('setGalleries', data);
  }
};
export const mutations = {
  setGalleries(state, data) {
    state.galleries.push(data);
  }
};在页面加载之前,在mixin中使用fetch从api返回数据。然而,我注意到,每次我导航到一个新页面时,它都在运行相同的fetch,并不断向Vuex状态添加重复数据。

如果我的状态已经存在,如何防止fetch运行并不断向我的状态添加重复数据?
发布于 2020-06-04 12:40:39
我不确定为什么这会让我如此纠结,但我找到了一个非常简单的解决方案。
async fetch() {
  if (this.galleries.length) return;
  await this.fetchGalleries();
}刚刚在fetch函数中添加了一个条件返回语句作为第一行。
https://stackoverflow.com/questions/62180822
复制相似问题