Vue fetch 被呼叫兩次
P粉593649715
P粉593649715 2024-01-03 14:09:31
0
1
480

我有這個程式碼片段:

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學習者快速成長!