首页  >  问答  >  正文

Vue fetch 被调用两次

我有这个代码片段:

export default defineComponent({
  name: "filter",
  props: {},
  setup() {
    const states = useCounterStore();
    return { states };
  },
  data() {
    return {
      items: [],
    };
  },
  methods: {},
  mounted() {
  fetch("http://localhost:3000/tags")
  .then((res) => res.json())
  .then((data) => {
    this.items = data;
    alert(data);
  })
  .catch((err) => console.log(err.message));
  },
});

fetch 被调用了两次,我不知道为什么。 有什么解决办法吗?

P粉593649715P粉593649715290 天前481

全部回复(1)我来回复

  • P粉269847997

    P粉2698479972024-01-04 11:27:32

    从共享代码来看,该组件似乎被安装了两次,因此您可能需要查看正在安装它的组件。

    但是,您可以存储响应,这样就不会多次获取

    const tags = ref(null);
    const tagsError = ref(null);
    const getTags = () => {
      fetch("http://localhost:3000/tags")
        .then((res) => res.json())
        .then((data) => {
          tags.value = data;
          return tags;
        })
        .catch((err) => tagsError.value = err.message;
    }
    
    export default defineComponent({
      name: "filter",
      props: {},
      setup() {
        const states = useCounterStore();
        if(tags.value === null) {
          getTags().then(() => this.items = [...tags.value]);
        } else {
          this.items = [...tags.value];
        }
        return { states };
      },
      data() {
        return {
          items: [],
        };
      },
      methods: {},
    });
    

    因为 tags 是在组件外部声明的,所以它的行为类似于全局变量,因此它是有状态的。每次组件设置时,它都会检查标签是否已加载,然后使用缓存的数据,或者加载它并在之后更新项目。

    关于该示例的一些注释...
    理想情况下,此类逻辑应位于单独的文件中并具有更好的抽象性。例如,如果您有多个 API,它们可以共享此功能,例如。 const {状态、数据、错误} = useApiCall('/tags')。并且您可以直接使用 tags,而不是使用 items,因为示例中的标签已经是 ref。还可能存在竞争条件,可以通过跟踪 API 调用状态来解决。

    回复
    0
  • 取消回复