Home > other >  get request with axios and vujes
get request with axios and vujes

Time:11-04

Good afternoon folks,

How can I send a Get request every time with a search button on my app?

I don`t want to download the whole JSON from the API just only the search results?

Many thanks.

That is my search bar:


     <div id="app">
        <div class="search-wrapper">
        <input type="text" 
               class="search-bar" 
               v-model="search"
               placeholder="Search in the titles"/>
          
      </div>

and this is the axios part I have :


      axios
        .get(
          `https://zbeta2.mykuwaitnet.net/backend/en/api/v2/media-center/press-release/?page_size=61&type=5`
        )
        .then((response) => {
          this.items = response.data.results;
        });

CodePudding user response:

Step 1: Create HTML template

<div >
  <form>
    <input
      type="search"
      @input="searchByTitle($event.target.value)"
      
      v-model="search"
      placeholder="Search by title"
    />
  </form>
</div>

Step 2: Add search by title method

searchByTitle(value) {
  clearTimeout(this.debounce);
  this.debounce = setTimeout(() => {
    if (value.length >= 3) {
      this.params = `q=${value}`;
      this.loadPressRelease();
    }
  }, 600);
},

We have to make the REST API call when there is 3 or more than 3 characters and added debounce once we stopped typing then only we are making REST API call

Step 3: Added watch for when clearing search text

watch: {
  search(newVal, oldVal) {
    if (oldVal && !newVal) {
      console.log("morning has broken...");
    }
    if (!newVal) {
      this.clearSearch();
    }
  },
},

Step 4: Added searchbar css style

.search-bar {
  border: 1px solid #ccc;
  outline: 0;
  border-radius: 10px;
  width: 50%;
  margin-left: 10px;
  padding: 0.5rem;
}
.search-bar:focus {
  box-shadow: 0 0 15px 5px #b0e0ee;
  border: 2px solid #bebede;
}
.search-box:not(:valid) ~ .close-icon {
  display: none;
}

DEMO

  • Related