【问题标题】:NuxtJS - Prevent fetch if data already exists in state?NuxtJS - 如果状态中已经存在数据,则阻止获取?
【发布时间】:2020-06-03 19:09:13
【问题描述】:

我有一个使用 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);
  }
};

fetch 在 mixin 中用于在页面加载之前从 api 返回数据。但是我注意到,每次我导航到新页面时,它都会运行相同的 fetch 并不断将重复数据添加到 Vuex 状态。

如果fetch 已经存在,我如何防止它运行并不断向我的状态添加重复数据?

【问题讨论】:

    标签: vue.js nuxt.js


    【解决方案1】:

    我不知道为什么这让我如此受挫,但我想出了一个非常简单的解决方案。

    async fetch() {
      if (this.galleries.length) return;
      await this.fetchGalleries();
    }
    

    刚刚在fetch 函数的第一行添加了一个条件返回语句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 2022-09-25
      • 1970-01-01
      • 2019-05-20
      相关资源
      最近更新 更多