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

Webpack attempts to duplicate files prior to compilation but I am anticipating the opposite outcome

I needed the copy plugin to run after compilation, which seemed like the logical order. However, I found myself having to compile using webpack twice every time in order to get the fresh version on production. It wasn't until later that I realized it ...

`I encountered some challenges while trying to integrate Firebase with my Vue.js application`

Currently, I am in the process of integrating Firebase into my Vue.js application. After setting up Vue.js using Vue CLI, installing firebase, vuefire, and bootstrap-vue, I attempted to retrieve data manually inserted into my database but encountered issue ...

Is the JavaScript file not being stored in the cache?

As I work on optimizing my web application, I am facing a challenge with a javascript file size of approximately 450K even after compressing it. While I intend to redo the javascripting in due time, for now, I need to go live with what I have. Initially, I ...

Using jQuery's .load() method to load a PHP file can result in an exponential increase in XHR finished loading time with each subsequent load

There seems to be an issue with my code using .load() to load a PHP page into a div whenever the navbar or link is clicked. After multiple clicks, I noticed that the "XHR finished loading" increases exponentially and it appears that the same PHP file is be ...

Establish a timeout period for ajax requests using jQuery

$.ajax({ url: "test.html", error: function(){ //do something }, success: function(){ //do something } }); At times, the success function performs well, but sometimes it does not. How can I add a timeout to this ajax re ...

Effortless navigation through the document in both directions with seamless scrolling

To achieve a specific scrolling behavior on my webpage, I implemented the following function. Here is the code snippet: $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $("html, body").animate({scrollTop: 700}, 500); re ...

Show off markdown formatting without the need for v-html

I run a unique type of platform that allows users to publish their own blog posts using a WYSIWYG editor, and then share them on the site. My top priority is to ensure security against XSS attacks, which is why I am looking for alternatives to using v-htm ...

SonarLint versus SonarTS: A Comparison of Code Quality Tools

I'm feeling pretty lost when it comes to understanding the difference between SonarLint and SonarTS. I've been using SonarLint in Visual Studio, but now my client wants me to switch to the SonarTS plugin. SonarLint is for analyzing overall pr ...

Watching the Event Emitters emitted in Child Components?

How should we approach utilizing or observing parent @Output() event emitters in child components? For instance, in this demo, the child component utilizes the @Output onGreetingChange as shown below: <app-greeting [greeting]="onGreetingChange | a ...

Tips for storing and replicating jQuery events

I am working on saving jQuery events in a database. // This Function is called On Click function trackevent(event){ window.events.push(event) } $.each(window.events, function(i, item){ console.log(i +" - "+ $.parseJSON(item)); }); The events a ...

What steps should I take to create code that can generate a JWT token for user authentication and authorization?

I'm struggling to get this working. I have a dilemma with two files: permissionCtrl.js and tokenCtrl.js. My tech stack includes nJWT, Node.js/Express.js, Sequelize & Postgres. The permission file contains a function called hasPermission that is linke ...

Load certain database information into memory as Express initializes

Are there any efficient methods for storing data in Express? For instance, I am interested in preloading all API keys from a PostgreSQL database into memory when the server is initialized to avoid having to query the database for each API request. I consi ...

The issue with displaying Fontawesome icons using @import in CSS-in-JS was not resolved

I recently changed how I was importing Fontawesome icons: src/App.css @import "@fortawesome/fontawesome-free/css/all.css";` After shifting the @import to CSS-in-Js using emotion: src/App.js // JS: const imports = css` @import "@fortawes ...

Implement an AJAX function to prompt a save dialog before initiating the download process

I'm currently programming an embedded device in C with a web server. One of the tasks I am working on is downloading files from this device. I need to download several files at once, so I've set up an AJAX request that uses a POST method and send ...

abandoning the upload of an item into a THREE.js environment

Currently, I am working on a THREE.js scene where I need to prevent uploading multiple files into the scene simultaneously. The setup involves using Angular to implement the three js scene and canvas as a factory to maintain only one instance of a canvas a ...

Comparing Optimistic Updates and Tag Invalidation in RTK Query

I found a basic code example from the RTK query documentation: updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({ query: ({ id, ...patch }) => ({ url: `posts/${id}`, method: 'PUT', ...

Angular front-end rendering with Rails backend integration

Currently, I am working on a medium-sized Rails application and my latest endeavor is to integrate Angular into the system. After reviewing several tutorials, it appears that the most common method for fetching initial data and displaying the first view in ...

What steps can I take to resolve the issue in my code? I keep receiving a type error stating that it cannot read

I seem to be encountering an issue when running my code where I receive a 'cannot read property 'age' of null'. This error breaks my code, and I'm trying to figure out how to implement a check to ensure it only runs when I am signe ...

Converting a PHP timestamp to a jQuery-compatible format

Can someone help me find the equivalent function in jQuery that will give me a time format similar to this: date( 'Y-m-d\TH:i:sP'); //the output is like this. 2013-10-30T18:10:28+01:00 I am looking for this specific format in jQuery to use ...

Using cfajaxproxy in conjunction with URL rewriting capabilities

I have successfully integrated the cfajaxproxy tag, but encountered an issue with the cfc's location in the root directory of my site. When accessing a page within the root directory through a rewritten URL (e.g. mysite.com/one/two/ -> mysite.com/two ...