Binding Data in Vue Multiselect

After extensive searching, I stumbled upon an amazing searchable select Vue component that has caught my eye: https://github.com/monterail/vue-multiselect.

However, there seems to be a small issue when it comes to feeding it an array of objects as options. The data binds to the entire object instead of just the value.

Interestingly enough, I came across an issue in the repository that was created 8 hours before my own quest began:

https://github.com/monterail/vue-multiselect/issues/263

I sense that I might be overlooking something obvious. Any assistance on this matter would be highly appreciated.

Answer №1

Utilize filter options and incorporate a custom label.

let categories = [
  {id: 1, name: "adam"},
  {id: 2, name: "michael"}
];

<multiselect 
  v-model="rule.id" 
  :options="categories.map(category => category.id)" 
  :custom-label="opt => categories.find(x => x.id == opt).name">
</multiselect>

To learn more, refer to the related discussion on this github thread.

Answer №2

As per the information in the documentation for vue-multiselect, it is stated that:

  • The array of available options can be Objects, Strings, or Integers.
  • If an array of objects is used, the visible label will default to option.label.
  • If the labal prop is provided, the label will be equal to option['label'].
  • @type {Array} */ options: { type: Array, required: true },

Therefore, it is expected to bind to the entire object from the provided list, and the option can be assigned to the object's label property like this:

[... { label: "option1", otherdata.. }, { label: "option2", otherdata.. }, ]...

Answer №3

I have developed a solution where an object receives the selected item from a vue-multiselect. It then sends this object using '@input' to trigger the function "listaCidades", which will only send the "id" to my API. Here is the code snippet for reference:

<multiselect                          
  v-model="selectedState"
  :options="stateList"
  :multiple="false"      
  label="description"
  track-by="description"
  :preselect-first="false"
  @input="cityList(selectedState.id)"
></multiselect>
cityList(stateId){
  //sending the selected id to the API
  this.$http
    .get(this.$apiURL + "/cities/list/" + stateId, {
      headers: {
        authorization: "Bearer " + this.user.token
      }
    })
    .then(response => {
      if (response.data.status) {            
        this.cityList = response.data.cityList;            
      }
    })
    .catch(function(error) {
      console.log(error);
    });
}

Answer №4

After updating to the latest version of vue-multiselect, I was able to successfully implement this code:

<multiselect
  v-model="store_front_id"
  track-by="id"
  label="name"
  :options="storefronts.map(i => i.id)"
  :searchable="false"
>
  <template slot="singleLabel" slot-scope="props">
    <span class="option__title">{{ getStoreFrontName(props) }}</span>
  </template>
  <template slot="option" slot-scope="props">
    <span class="option__small">{{ getStoreFrontName(props) }}</span>
  </template>
</multiselect>

computed: {
    ...mapState('storefront', ['storefronts']),
},
methods: {
    getStoreFrontName(props) {
        return this.storefronts.find(i => i.id === props.option).name
    },
}

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's the best way to ensure you're linting the correct file type for importing in Web

Upon installation of WebStorm, I encountered an issue when opening an existing Vue/TypeScript project. The IDE was not correctly importing and linting some file imports that were functioning properly through ESLint/webpack. In my usage of Vue 2.x with com ...

Sending data from PHP to JavaScript using AJAX

I'm encountering an issue trying to pass data from a PHP file to a JavaScript file using echo. My PHP file contains the following code snippet: <?php ...establishing connection and retrieving list from database... for($i=0;$i<sizeOf($li ...

How can I transfer an array of objects obtained from an ajax call to an observable array?

One of my functions involves making an ajax call and receiving data in the callback. It looks something like this: function fetchData(callback) { //perform ajax if(callback) { callback(data.data); } } If I use the function like this: fetc ...

Guide on replacing the "read more" text with a Vuetify icon in a Vue.js application

I am currently working on creating a photo and description display as shown below. Any ideas on how I can replace the "read more" and "read less" text with arrow icons (up and down)? <template> <v-col cols="6" > ; <row align= ...

Navigate through a nested JSON structure and update the data points

In my possession is a JSON tree structured as follows: { "projects": { "Proj1": { "milestones": { "default": "20150101", "default2": "20140406", "default3": "20140101", ...

What could be the reason for my Node.js Express response coming back as empty?

While working on a registration system, I have encountered an issue. When errors occur in the form, I receive the correct error messages. However, when a user with the same email attempts to register and triggers 'res.json({error: 'email exists& ...

Getting started with TinyMCE in Nuxt: A step-by-step guide

I need to incorporate this script into my Nuxt code: <script> tinymce.init({ selector: "#mytextarea", plugins: "emoticons", toolbar: "emoticons", toolbar_location: "bottom", menubar: false ...

Nuxtjs component fails to hot reload when v-if condition is modified

I am facing an issue with my navbar component which consists of two buttons, "Logout" and "Dashboard", that are visible only when the user is authenticated using v-if condition. The problem arises when the user clicks on the Logout button as the navbar do ...

Quasar version 2 (Vue) introduces an exciting new feature in the QTable component - the ability to

Could someone provide some guidance on how to create a table with nested elements like the one shown in the screenshot? View table image here I am facing an issue connecting additional drop-down lines within the table. Is there functionality available fo ...

Animating a camera along a predefined path in A-Frame to maintain focus on a subject

I have been experimenting with animating a camera using the alongpath component, but I am struggling to keep the camera focused on a target. Despite trying both orbit-controls and look-at components, I can't seem to get them to work properly. It seems ...

Error detected (unresolved promise): Invalid JSON format is causing an Unexpected token < at the beginning of data position (Application built with React/Redux)

I'm in the process of setting up user authentication using JWT. I've successfully created an API for this purpose. Now, my goal is to integrate this authentication API with my React/Redux App. When a user signs up, I trigger an action from my S ...

Ways to determine if the backbone.js model has been emptied

I often find myself wondering how to determine if a model has been cleared or is empty. For example, if I set the model with: model.set({name:'this is a test', id:1}); and then clear it with: model.clear(); ...

Substitute regular expressions with several occurrences by their respective capture groups

I am attempting to use JavaScript to extract only the link text from a string and remove the href tags. The expected behavior is as shown below: <a href='www.google.com'>google</a>, <a href='www.bing.com'>bing</a> ...

developing a shader that transitions between day and night based on the movement of a light source

I've set up a scene with a sphere illuminated by a DirectionalLight to simulate the sun shining on Earth. My goal is to incorporate a shader that displays the earth at night on the unlit portions of the globe and during the day on the lit areas. Event ...

Is it possible to prompt npm to install a sub-dependency from a GitHub pull request?

Currently, I'm in the process of setting up geofirestore, which has a dependency on geofirestore-core. However, there is an existing bug in geofirestore-core that has been addressed in a pull request. How can I make sure that my geofirestore installa ...

Tips for loading images dynamically (or lazily) as they come into the user's view with scrolling

Many modern websites, such as Facebook and Google Image Search, display images below the fold only when a user scrolls down the page enough to bring them into view (even though the page source code shows X number of <img> tags, they are not initially ...

What makes Angular date pickers sluggish?

Have you ever noticed that Angular JS date pickers consume a lot of CPU? When multiple date pickers are present on a page, they can noticeably reduce the site's speed. Is there a way to minimize this issue? Take for example the official Angular for ...

What is the procedure for obtaining a Connect server's host name and port number?

Just like the example shown in this Express-related question, I'm wondering if there is a way to programmatically retrieve the host name and port number of a running Connect server? ...

Press the div using JavaScript and jQuery

Is it possible in JavaScript to automatically click on a hidden div once it is displayed? For instance, imagine we have a div with the style "display:none;" like so: <div style="display:none;" id="button">Hello World</div> Once this div&apos ...

Exploring the attributes of ExtJS display objects

I am looking for a way to efficiently display JSON content from a servlet in a browser using a list format. While I could use the definition list tag in pure HTML, I need to load everything dynamically without manually parsing and creating the HTML code. ...