Binding Vue MultiSelect Checkboxes to Data Model

The data properties of the multi-select component are not updating when changed. The checkboxes are not being updated on the front-end.

Expected Behavior: The checkboxes should get ticked when clicked.

Link to code: https://jsfiddle.net/bzqd19nt/3/

<div id="app">
  <multiselect 
    select-Label=""
    selected-Label=""
    deselect-Label=""
    v-model="value" 
    :options="options"
    :multiple="true"
    track-by="library"
    :custom-label="customLabel"
    :close-on-select="false"
    @select=onSelect($event)
    @remove=onRemove($event)
    >
    <span class="checkbox-label" slot="option" slot-scope="scope" @click.self="select(scope.option)">
    {{ scope.option.library }}
      <input class="test" type="checkbox" v-model="scope.option.checked" @focus.prevent/>

    </span>
  </multiselect>
  <pre>{{ value }}</pre>
</div>
new Vue({
  components: {
    Multiselect: window.VueMultiselect.default
  },
  data: {
    value: [],
    options: [
      { language: 'JavaScript', library: 'Vue.js', checked: false },
      { language: 'JavaScript', library: 'Vue-Multiselect', checked: false },
      { language: 'JavaScript', library: 'Vuelidate', checked: false }
    ]
  },
  methods: {
    customLabel(option) {
      return `${option.library} - ${option.language}`;
    },
    onSelect(option) {
      console.log('Added');
      option.checked = true;
      console.log(`${option.library}  Clicked!! ${option.checked}`);
    },

    onRemove(option) {
      console.log('Removed');
      option.checked = false;
      console.log(`${option.library}  Removed!! ${option.checked}`);
    }
  }
}).$mount('#app');

Answer №1

Within your code, you are calling the onSelect function and attempting to modify the option argument inside the function:

option.checked = true;

This change only applies to the local variable option (the function argument) and does not affect the objects in the options array within the data of the Vue instance, which are linked to checkboxes. This is why nothing happens when you click on an option in the list.

To correct this issue, locate the appropriate element in the options array and update it:

let index = this.options.findIndex(item => item.library==option.library);
this.options[index].checked = true;

Below is the corrected code snippet:

new Vue({
components: {
  Multiselect: window.VueMultiselect.default
},
data: {
  value: [],
  options: [
    {language: 'JavaScript', library: 'Vue.js', checked: false },
      { language: 'JavaScript', library: 'Vue-Multiselect', checked: false },
      { language: 'JavaScript', library: 'Vuelidate', checked: false }
    ]
},
  methods: {
  customLabel (option) {
      return `${option.library} - ${option.language}`
    },
    onSelect (option) {
    console.log("Added");
      let index = this.options.findIndex(item => item.library==option.library);
      this.options[index].checked = true;
      console.log(option.library + "  Clicked!! " + option.checked);
    },
    
    onRemove (option) {
    console.log("Removed");
      let index = this.options.findIndex(item => item.library==option.library);
      this.options[index].checked = false;
      console.log(option.library + "  Removed!! " + option.checked);
    }
  }
}).$mount('#app')
* {
  font-family: 'Lato', 'Avenir', sans-serif;
}

.checkbox-label {
  display: block;
}

.test {
  position: absolute;
  right: 1vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d6b68783070687169746e7871787e695d2f332d332f">[email protected]</a>/dist/vue-multiselect.min.css" rel="stylesheet"/>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2a4a7b7ffbfa7bea6bba1b7beb7b1a692e0fce2fce1">[email protected]</a>/dist/vue-multiselect.min.js"></script>
<div id="app">
  <multiselect 
    select-Label=""
    selected-Label=""
    deselect-Label=""
    v-model="value" 
    :options="options"
    :multiple="true"
    track-by="library"
    :custom-label="customLabel"
    :close-on-select="false"
    @select=onSelect($event)
    @remove=onRemove($event)
    >
    <span class="checkbox-label" slot="option" slot-scope="scope" @click.self="select(scope.option)">
    {{ scope.option.library }}
      <input class="test" type="checkbox" v-model="scope.option.checked" @focus.prevent/>
      
    </span>
  </multiselect>
  <pre>{{ value }}</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 reason behind VueJS animations only functioning in a single direction?

I'm completely baffled by this issue. It seems that Vue3 is able to apply the move animation class correctly for a <transition-group/> when there is a list of items, but this only happens if the list is moved forward. I've created a CodePen ...

Creating a custom function for pagination in a Vuetify data table

Currently, I am dealing with JSON data that has been pre-paginated by the server. The challenge I am facing is integrating a custom function into my Vuetify data table pagination to dynamically load the next or previous batch of data from the server. Howev ...

Discovering latitude and longitude coordinates from a map URL, then enhancing dynamism by utilizing the coordinates as parameters

Hello, I am currently learning Vue.js and have encountered a challenge with embedding Google Maps URLs. Despite my extensive research on Google, I have not been able to find the solution I need. Here is an example of the URL I am working with: "https: ...

Converting an array of objects into a flat array of objects with Javascript

My data array requires conversion to a flattened array returning new header and data. For instance, the first object contains a name with three data points: "title, first, last." The desired output is: From : { gender: 'male', name: { ...

Getting access to props within a child component's mounting phase

It is commonly understood that when the child component is mounted before the parent component, trying to access props in the child component's mounted period will result in null. However, I recently came across a scenario where props were successful ...

"Looking to display an image object retrieved from AWS S3 using a signed URL in Vue.js? Here's how you

<div v-for="(data, key) in imgURL" :key="key"> <img :src= "getLink(data)" /> </div> imgURL here is an array that contains file names. methods: { async getLink(url){ let response = await PostsService.downloadURL({ i ...

Sending new props when navigating back using $navigateBack

I created an overview page where users can view their results. They have the option to edit a value by clicking on the edit button, which navigates them to another page for making changes. However, upon returning to the overview page after editing, I notic ...

Find the highest-level parent element using JQUERY and select all of its child divs excluding the current

<div class="topDiv"> <div class="repeaterDiv"><input type="radio" id="rpt_01_rb" /> <input type="checkbox" id="rpt_01_cb1" /> <input type="checkbox" id="rpt_01_cb2" /> <input ty ...

How can I retrieve the `checked` state of an input in Vue 3 using Typescript?

In my current project, I am using the latest version of Vue (Vue 3) and TypeScript 4.4. I am facing an issue where I need to retrieve the value of a checkbox without resorting to (event.target as any).checked. Are there any alternative methods in Vue tha ...

Cannot utilize structuredClone() on the value of the reference variable

I am looking to implement the structuredClone() function in my Vue application. I want to use it for creating a deep clone without resorting to methods like stringify and parse or third-party libraries. In my setup function, the following code works fine: ...

What could be the source of the error message: "Error: .eslintrc.js: The environment key 'vue/setup-compiler-macros' is not recognized

I am currently working on a sample application using Vue 3 and Typescript. Specifically, I have opted for the new Vue v3.2 setup option within the section of the Vue SFC. Following the guidance from the Vue documentation, I included "vue/setup-compiler-ma ...

Keep a close eye on your Vue app to make sure it's

<template> <v-form :model='agency'> <v-layout row wrap> <v-flex xs12 sm12 lg12 > <v-layout row wrap> <v-flex xs12 md12 class="add-col-padding-right"> <v-radio-group v-mod ...

What strategies can be implemented to decrease the size of the app.js file with such a bulky bundle size

Utilizing Vue.js in my project with just 4 components. Imported dependencies are restricted to bootstrap, jquery, and lodash: import { map } from 'lodash'; import 'bootstrap/js/dist/modal'; import $ from "jquery"; The issue ...

"Troubleshooting issue: No response received when uploading files in VueJs3 with Laravel 8

Seeking assistance with a persistent issue that I have been unable to resolve despite trying various methods. Your help would be greatly appreciated. Below is my Vue template for creating categories: <form @submit.prevent="createCat" enctype= ...

Error in Vue.js: When using v-for, it is not possible to read a property

I'm working on creating multiple FAQ boxes using a list of objects containing questions and answers. However, I keep encountering the error message "Cannot read property 'question' of undefined." What could be causing this issue? Here's ...

Troubleshooting issue: Displaying input based on selected option not functioning

<custom-select label="Target Type" v-model="targetType" name="targetType" placeholder="Select Target Type" data-test="overall-type-input" :options="targetTypeOptions ...

Uncovering the secrets of connecting a JSON object with VueJS and AXIOS

How do I map the JSON object with a variable? I'm unsure if my code is correct as I'm just starting to study Vue.js. Please review my code where I want to map JSON data to the 'country' variable. var appZone = new Vue({ el: '# ...

Tips for utilizing a primary template within a secondary container

In my code snippet below, I have outlined two steps: "step===1" and "step===2". My goal is to reuse the step 1 template for step 2. This means that after completing step 1 and clicking on the next button, I want to show the same template again for reusabil ...

Retrieving the current data value by utilizing a specific method

Looking for help with this html component: <div class="col-md-3"> <button class="btn btn-light" @click.prevent="switchCurrency" :currency="cad">Canadian dollar</button> <br/> <s ...

Enhancing the default vue-cli webpack app with additional components

To ensure reproducibility, I began by setting up a basic project using vue-cli: npm install -g vue-cli vue init webpack spa cd spa npm install npm run dev Afterwards, I decided to swap out the Vue logo with an app-header component. Here's how I impl ...