Vue fetch 被调用两次
P粉593649715
P粉593649715 2024-01-03 14:09:31
0
1
478

我有这个代码片段:

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粉593649715
P粉593649715

全部回复(1)
P粉269847997

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

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

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 调用状态来解决。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!