首頁  >  問答  >  主體

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 天前487

全部回覆(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
  • 取消回覆