[Vuejs]-How to import data from API to use as Fuse list in Vue app

0👍

Ok, I’ll give you a working pen, more of a proof of concept than anything else.

https://codepen.io/rifi2k/pen/wRXpWE

Vue.prototype.$http = axios;
new Vue({
  el: '#app',
  mounted() {
    var options = {
      shouldSort: true,
      threshold: 0.6,
      location: 0,
      distance: 100,
      maxPatternLength: 32,
      minMatchCharLength: 1,
      keys: [
        "name",
        "email"
      ]
    };
    
    this.$http.get('https://jsonplaceholder.typicode.com/users').then((response) => {
      console.log(response);
      this.list = response.data;
      this.fuse = new window.Fuse(this.list, options);
      this.result = this.list
    }, (err) => {
      console.log(err)
    });

  },
  watch: {
    search() {
      if (this.search.trim() === '')
        this.result = this.list
      else
        this.result = this.fuse.search(this.search.trim())
    }
  },
  data: {

    fuse: null,
    search: '',
    list: [],
    result: []

  }

});

So for starters you don’t need to put the fuse library into the window because including the script from the CDN will already take care of that for you.

We are going to use the Vue prototype to set the global axios to $http. This way you can use it in any Vue component with this.$http

Then we are going to make a GET request to our API with axios which returns a promise with our response which contains the JSON data. We can use promise .then to make sure we are waiting until the API has returned us the data. Then we stick all the rest of the work depending on the API call being finished inside of the promise .then so that it cannot run until we have our data.

Also a more modern way to do this would be Async Await.

Leave a comment