Vue multiselect not removing options

Viewed 3902

I have a working example of vue-multiselect. This is working as expected with the two remaining issues.

  1. When you try and remove an option by clicking the x, it in fact duplicates the option, and never removes it
  2. The loading spinner never disappears even though I reset the isLoading var to false

Example: https://codepen.io/TheDevCoder/pen/bGVbGOG

Markup

<multiselect
    v-model="value"
    id="ajax"
    label="full_name"
    :options="store"
    :multiple="true"
    :loading="isLoading"
    :internal-search="false"
    @search-change="getData"
    >
</multiselect>

Script

getData(query){
    this.isLoading = true;
    if(query.length > 0){
        axios.get(`https://api.github.com/search/repositories?q=${escape(query)}`)
            .then((res) => {
                this.store = res.data.items;
                this.isLoading = false;
            })
            .catch((error) => {
                console.log(error);
                this.isLoading = false;
            });
    }
}
2 Answers

Answer for your first issue

(When you try and remove an option by clicking the x, it in fact duplicates the option, and never removes it)

you need to specify :track-by="id" // or whats is your unique key

As you already correctly pointed out, there are 2 unrelated issues in your code.

When you try and remove an option by clicking the x, it in fact duplicates the option, and never removes it

Since you're working with objects in your multiselect, you have to define an attribute that the multiselect can use as key. The key is then used to identify the element to remove from the selection. Check the official doc for more information. In your case, you could take the id since it's unique. Therefore set the track-by prop of the multiselect component.

<multiselect
  v-model="value"
  id="ajax"
  label="full_name"
  :options="store"
  :multiple="true"
  :loading="isLoading"
  :internal-search="false"
  @search-change="getData"
  track-by="id"

></multiselect>

The loading spinner never disappears even though I reset the isLoading var to false

You're only resetting the isLoading variable if you're entering you're if condition. But what happens if your search query is empty? Hence, you should move the isLoading = true statement as well into the code executed conditionally.

getData(query) {
  if (query.length > 0) {
    this.isLoading = true; // TODO: set the loader to true only if you're really searching
    this.queryData = JSON.parse(JSON.stringify(query));
    this.$http
      .get(`https://api.github.com/search/repositories?q=${escape(query)}`)
      .then(res => {
        this.store = res.data.items;
        this.isLoading = false;
      })
      .catch(error => {
        console.log(error);
        this.isLoading = false;
      });
  }
}

You can check out this fiddle which has a fixed version of your code: https://codepen.io/ug27/pen/abvoqjz

Related