vueでaxiosを使用してリクエストをキャンセル

1135 ワード

new Vue({
  el: "#app",
  data: {
      searchItems: null,
      searchText: "some value",
      cancelSource: null,
      infoText: null
  },
  methods: {
    search() {
      if (this.searchText.length < 3)
      {
        return;
      }

      this.searchItems = null;
      this.infoText = 'please wait 5 seconds to load data';

      this.cancelSearch();
      this.cancelSource = axios.CancelToken.source();

      axios.get('https://httpbin.org/delay/5?search=' + this.searchText, {
        cancelToken: this.cancelSource.token }).then((response) => {
          if (response) {
            this.searchItems = response.data;
            this.infoText = null;
            this.cancelSource = null;
          }
        });
    },
    cancelSearch () {
      if (this.cancelSource) {
        this.cancelSource.cancel('Start new search, stop active search');
        console.log('cancel request done');
      }
    }
  }
})

原文リンク:https://stackoverflow.com/a/5...