Using Axios to fetch data and populating select dropdown options in a Vue component

I am currently working on integrating the response data values with my multiselect options. Although the console log displays the returned results, I'm facing difficulty in connecting them to my multiselect options.

When I enter 'Day' into my multiselect, an autocomplete function triggers the axios call to fetch matching options, and the console shows:

 0:
    tag_id:  "1001"
    tag_data: "First Day"
 1:
    tag_id:   "1002"
    tag_data: "Second Day"

How can I incorporate these returned values into my options?

  <div id="tagApp">
      <multiselect
      v-model="value"
      :options="options"
      :loading="loading"
      :multiple="true"
      :taggable="true"
      @search-change="val => read(val)"
      ></multiselect>
  </div>

new Vue({
      components: {
        Multiselect: window.VueMultiselect.default
      },
      el: "#tagApp",
      data() {
        return{
            value: [],
            loading: false,
            options: []
        }

      },
      methods: {
        read: function(val){
            //console.log('searched for', val);
          if (val) {
            this.loading = true;
            this.options = [];

            const self = this;
            console.log(val);

            axios.get('campaigns/search',{params: {query: val}})
                .then(function (response) {
                    self.options = response.data;
                    console.log(response.data);
            });

          } else {
            this.options = [];
          }
        }
      }
    })

Answer №1

To properly use objects as options, you must include the label and track-by properties in the multiselect component. Detailed information can be found in the documentation here

<multiselect
  v-model="value"
  label="tag_data"
  track-by="tag_id"
  :options="options"
  :loading="loading"
  :multiple="true"
  :taggable="true"
  @search-change="val => read(val)"
></multiselect>

Answer №2

Make sure to include both the label property and the track-by property in your code. In my case, I used the title property from the object assigned to the options variable. You should choose a property name that is present in the array you are using as options.

Check out this CodePen link for reference: https://codepen.io/oze4/pen/ROVqZK?editors=1010

Vue.component("multiselect", window.VueMultiselect.default);

new Vue({
  el: "#app",
  data: {
    value: [],
    options: []
  },
  mounted() {
    var self = this;
    axios
      .get("https://jsonplaceholder.typicode.com/todos?_start=1&_end=10")
      .then(response => {
        self.options = response.data;
      })
      .catch(error => {
        alert(error);
      });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2a4a7b7ffbfa7bea6bba1b7beb7b1a692e0fce3fce2">[email protected]</a>/dist/vue-multiselect.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99f9c8cc4849c859d809a8c858c8a9da9dbc7d8c7d9">[email protected]</a>/dist/vue-multiselect.min.css">

<div id="app">
  <label class="typo__label">Simple select / dropdown</label>
  <multiselect 
    v-model="value" 
    :height="300"
    :options="options" 
    :multiple="true" 
    :close-on-select="false" 
    :clear-on-select="false" 
    :preserve-search="true" 
    placeholder="Pick some" 
    label="title" 
    track-by="title" 
    :preselect-first="false"
  >
    <template slot="selection" slot-scope="{ values, search, isOpen }"><span class="multiselect__single" v-if="values.length &amp;&amp; !isOpen">{{ values.length }} options selected</span></template>
  </multiselect>
  <pre class="language-json"><code>{{ value }}</code></pre>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the purpose of $ and # in the following code snippet: $('#<%= txtFirstName.ClientID%>')

$('#<%= txtFirstName.ClientID%>').show(); Attempting to pass the ClientId as a parameter from server tags to an external JavaScript file. <input type="text" ID="txtFirstName" runat="server" maxlength="50" class="Def ...

interactive switch using font awesome icons and jquery

Initially, I assumed this would be an easy task, but I've encountered some difficulties in making it function smoothly. Although I am able to toggle once using .show and .hide, I am unable to toggle back. Any assistance would be greatly appreciated. ...

Unable to alter state from the onClick event of a dialog button

In the process of developing a Next.js app, I encountered an interesting challenge within one of the components involving a DropdownMenu that triggers a DialogAlert (both powered by Shadcn components). The issue arises when attempting to manage the dialog& ...

I'm experiencing some difficulties utilizing the return value from a function in Typescript

I am looking for a way to iterate through an array to check if a node has child nodes and whether it is compatible with the user's role. My initial idea was to use "for (let entry of someArray)" to access each node value in the array. However, the "s ...

What is the process for adding an event listener in React?

Currently, I am working on a chat application that involves both users and agents. I am facing an issue where I need to retrieve messages when the agent responds using a separate Rainbow UI. According to the documentation, this can only be achieved using a ...

I'm having trouble loading my Google Maps widget. Everything was functioning flawlessly until I attempted to hide it using the .hide function

After successfully implementing a Google Maps widget, I encountered an issue when trying to toggle its visibility using jQuery. Despite clicking on a div element to reveal the widget, the map fails to load inside the designated container. It seems as tho ...

Looking for a bootstrap table code that includes checkboxes and a save button, so that when the save button is clicked, it

Seeking a Bootstrap table code that includes row checkboxes. When the save button is clicked, it should return the selected checkbox rows. ...

How can I use jQuery to set up form validation for an input textfield?

Check out this code snippet: <form data-test="loginForm-container" novalidate="" method="POST" enctype="multipart/form-data"> <div class="css-o5d3v1 e1ovefus2"> <div data-test="guestForm-email-wrapper" class="e1ovefus1 css-yjv4po e1eu3s ...

Steps to ensure that Vue data is updated to accurately reflect any modifications made by user input in the HTML

I'm currently using Vue to develop a small application that involves copying dynamic HTML content to the user's clipboard once they have completed a form. While everything seems to be functioning correctly, I am encountering an issue where the ch ...

Configuring Axios header in Java backend based on the value stored in the express session

I am currently working on a frontend app using node.js express for server-side rendering. This app calls java backend endpoints and I use Axios to make the requests. A specific header named "agent-id" needs to be set in every request that is sent from expr ...

Supply a JSON parameter as a variable into the .load() function

When a button is clicked, I am attempting to load a page using the .load() method with a POST request. The URL parameters are generated and displayed as JSON formatted in the button attribute btn-url. Problem: The parameter is not being passed to the .loa ...

The output from the Moment.js HTTP server is currently experiencing errors and is not displaying the expected

My first time working with JavaScript and the Momentjs library has not been smooth sailing. I am facing an issue where the output is not displaying as required. The goal is to show dates in the format "Day, date month year" (e.g., Tuesday, 14th May 2018). ...

The intervals in hooks seem to be malfunctioning and not updating the date and time as expected

I am trying to continuously update the date and time every minute using React hooks. However, I am facing difficulty in updating the time properly. const Link = (props) => { let date = new Date(); const [dateTime, setDateTime] = useState({ cu ...

Toggle sidebar: expand/collapse

Looking for some assistance with my website project. I currently have two arrows to open and close the sidebar, but I would like one button to handle both actions instead. Can someone help me edit my code snippet to achieve this? Keep in mind that I am new ...

sliding effect of the background image

Currently, I am in the process of creating a navigation system that includes a background image slide effect. My goal is to mimic the design of a specific website: http://tympanus.net/Tutorials/BeautifulBackgroundImageNavigation/ However, my challenge lie ...

Delayed response of text effects in JQuery on page load

Within my rails app, I have the following code snippet: window.onload = -> $("#mycontainer").typewriter() $("#div1").fadeIn("slow") This code snippet interacts with the following block of content: <blockquote class="pull-left"> < ...

Set up an event listener for when geolocation permission is approved

My Setup: I've written some basic code snippet below: const onSuccess = () => { console.log('success'); } const onError = () => { console.log('error'); } navigator.geolocation.getCurrentPosition(onSuccess, onError) ...

Is there a way to prevent Vetur from automatically converting colSpan and rowSpan tags?

Currently, I am utilizing nativescript-vue and I require the colSpan and rowSpan tags to remain unchanged. The code formatter in Vetur changes rowSpan="2" to rowspan="2". Is there a way to deactivate the automatic lowercasing feature o ...

Ways to extract individual values from a Json Array and utilize them individually

I have a JSON data structure that I need to parse and separate each field into different arrays, so that I can use them individually. For instance, I want to split my data into two rooms: room 1 and room 2. After separating the data, I need to format it a ...

Looking to conceal the input div without compromising the functionality in Angular 14

Here is the provided HTML code for scanning a barcoder and assigning it to the barCodeNumber variable. The onChange() function will be called once the barcode is scanned. Question: How can I hide the div on the UI while still allowing the function to work ...