取消之前在 Vue JS 中使用 fetch API 进行的调用

Soh*_*dia 5 laravel vue.js

我正在 laravel + VueJS 应用程序中工作。其中有一个搜索功能,用户可以通过该功能搜索任何文本,然后将调用 API 以根据搜索文本获取数据。因此,要在 laravel 中调用 API,请使用 VueJS 中的“Fetch API”。所以现在,当任何用户按下任何关键字时,每次都会调用该方法来获取结果。因此,由于已发送多个请求。我只是喜欢在任何用户键入任何文本时这样做,然后每次以前的请求都必须取消。我在下面附加的代码用于调用 API 并获取数据。

            searchProperties(search) {

            if (search != null && search != '') {
                this.review = false;
                this.clearSes = false;
                fetch('/search/' + search)
                    .then(res => res.json())
                    .then(res => {
                        if (res.status === 200) {
                            this.properties = res.data.properties;
                        }
                    });

            } else {
                this.clearSuggestions();
            }
        }
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Ven*_*iun 1

你可以abortable fetch像这样

const controller = new AbortController();
const signal = controller.signal;

setTimeout(() => controller.abort(), 5000);

fetch(url, { signal }).then(response => {
  return response.text();
}).then(text => {
  console.log(text);
});
Run Code Online (Sandbox Code Playgroud)

请参阅文档了解更多详细信息。