Guide on creating multiple instances of vue-multiselect with a simple button click

I am trying to implement a vue-multiselect dropdown with the addition of a new dropdown upon clicking an "add more" button.

However, I am currently unsure of the best approach to achieve this.

Problem/Question: When adding 2 dropdowns, if the same option is selected in one dropdown, it is automatically selected in the other dropdown as well. I want to prevent this behavior.

Note: Each click of the "add more" button should create a separate instance of vue-multiselect.

var app = new Vue({
  el: '#app',
  components: { Multiselect: window.VueMultiselect.default },
  data () {
    return {
       value: "",
       options:['Calender','Range','Amount'],
       
       multiselectList:[],
    }
  },
  methods:{
      AddMoreMultiselect(){
         this.multiselectList.push('1 more multiselect'); 
      },
      remove(index){
          this.multiselectList.splice(index,1)
      }
  },
})
#app{
  //margin-top:30px;
}


.items{
    display: flex;
    justify-content: space-between;
}

.multiselect{
    width: 80%;
 }
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a4c4f564e53495f565f594e7a08140b140a">[email protected]</a>"></script>
  <link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b4d4e5e574e575648575f52485e575e584f7b09150a150b">[email protected]</a>/dist/vue-multiselect.min.css">
  <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
  
  


<div id="app">

   <div><button @click="AddMoreMultiselect()">Add More</button></div>

    <div class="items" v-for="(multiselect,index) in multiselectList" :key="index">
         <multiselect
        v-model="value"
        :options="options"
         :multiple="false"
        :taggable="false"
      ></multiselect>
      <div><button @click="remove(index)">Remove</button></div>
   </div>
</div>

Answer №1

Declare value as an empty array and then connect each selection to the corresponding value in that array based on the loop index v-model="value[index]":

var app = new Vue({
  el: '#app',
  components: {
    Multiselect: window.VueMultiselect.default
  },
  data() {
    return {
      value: [],
      options: ['Calendar', 'Range', 'Amount'],

      multiselectList: [],
    }
  },
  methods: {
    AddMoreMultiselect() {
      this.multiselectList.push('Add one more multiselect');
    },
    remove(index) {
      this.multiselectList.splice(index, 1)
    }
  },
})
#app {
  //margin-top:30px;
}

.items {
  display: flex;
  justify-content: space-between;
}

.multiselect {
  width: 80%;
}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e7f6e6aecee6fff7eaf0e6ef8c38686967698">[email protected]</a>"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="305256467e3e566e777f62686e776e686743060a050a04">[email protected]</a>/dist/vue-multiselect.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>

<div id="app">

  <div><button @click="AddMoreMultiselect()">Add One More</button></div>

  <div class="items" v-for="(multiselect,index) in multiselectList" :key="index">
    <multiselect v-model="value[index]" :options="options" :multiple="false" :taggable="false"></multiselect>
    <div><button @click="remove(index)">Remove</button></div>
  </div>

</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

Struggling with this mixed content problem

Encountering a problem while loading a js file: https://code.jquery.com/jquery-1.11.1.min.js, which is being loaded on my webpage in this manner: <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> Upon loading my webpage, an ...

Steps to include a personalized function in a Mongoose Model

One way to extend Mongoose is by adding methods to documents. Here's an example: const userSchema = new mongoose.Schema({ balance: Number }) userSchema.methods.withdrawBalance = function(amount){ const doc = this doc.balance = doc.balance - amou ...

Ways to exclusively display map items matching those in the array

Hey everyone, I'm dealing with a map that looks like this: Map { '708335088638754946' => 38772, '712747381346795670' => 12051, '712747409108762694' => 12792 } Alongside this map, I also have an array: let arr ...

Puppeteer patiently waits for the keyboard.type function to complete typing a lengthy text

Currently, I am utilizing puppeteer for extracting information from a particular website. There is only one straightforward issue with the code snippet below: await page.keyboard.type(data) await page.click(buttonSelector) The initial line involves typin ...

When displaying a collection of components, clicking a button will always select the most recent element in the array

Can you explain why this code won't work in a React environment? Every time the button is clicked, it picks up the value "name" from the last element in the array. In this example, the dialog will always display the name "John2". import React from "r ...

Utilizing Axios Instances for Authorization in Next.js Data Fetching

I am currently utilizing NextJS version 12.0.10 along with next-redux-wrapper version 7.0.5. I have implemented an Axios custom instance to store the user JWT token in local storage and automatically include it in every request, as well as to handle errors ...

Tips for accessing the value of a specific key within an object that is nested in an array

I'm attempting to extract the name of the merchant from within this specific array: [ { "model": "inventory.merchant", "pk": 1, "fields": { "merchant_name": "Gadgets R Us", "joined": "2020-01-06T07:16:17.365Z" } }, ...

Executing a query with a `has many` relationship in MongoDB: Step-by-step guide

In my setup with Node, Express, and backbone, I am successfully retrieving records from MongoDB collections using simple queries. However, I am struggling to understand how to query more complex data, such as the one below: db.employees.aggregate( [ ...

Incorporating a remote PHP file into your website using JavaScript

Is it feasible to utilize JS (jQuery) for executing a $.post from any website on any domain to a script on my server? This query stems from my reluctance to disclose my PHP files to clients (and avoid spending money on ionCube or similar solutions). By se ...

Display data fetched from concurrent Ajax calls in a React Component

I am currently in the process of converting my original project to Reactjs. Since I am new to this and it's my first application, I could use some guidance on how to effectively implement this in a React-friendly way and enhance both my skills and the ...

The battle between dynamic PDF and HTML to PDF formats has been a hot

In my current project, I am developing multiple healthcare industry dashboards that require the functionality to generate PDF documents directly from the screen. These dashboards do not involve typical CRUD operations, but instead feature a variety of char ...

Organize results from MySql using php

Trying to retrieve table values from a MySQL database sorted has proven to be a challenge for me. While I am able to connect and update the table successfully, I struggle with displaying the messages in the HTML chat history sorted by time. Is there a mo ...

The issue of Basic Bootstrap 5 Modal triggering twice is causing a frustrating experience

My modal is almost working perfectly - it changes content based on the clicked image, but it is triggering twice in the backend and I can't figure out why! I followed Bootstrap's documentation for this, so I'm unsure where the issue lies. Al ...

Testing vue.js components through vue-loader with dependency injection

I am currently experimenting with testing my Vue.js component using vue-loader, a webpack loader. I tried following the tutorial provided by vue-loader but encountered unexpected issues. Below is the code snippet for my component: <template> <h ...

Axios fails to populate store upon component mounting

I'm facing a state management issue. I am able to fill my state and display it on the frontend, but the problem arises with the timing of state filling. Every time I compile my project and visit the specific page, 'title: test' is displayed ...

Tips for deleting a hashtag from a URL

import router from './router' Vue.use(router) new Vue({ el: '#app', router, template: '<App/>', components: { App } }) In my main.js file, I have this code snippet. In another file name ...

Leveraging async/await in express

I am encountering an issue with my app.post method while trying to deploy on Firebase. The error message reads: Parsing error: Unexpected token =>. I am fairly new to node.js and Javascript as I primarily work with Swift. However, I require this code fo ...

Creating dynamic <a> tags using JavaScript

My current view includes a div tag with 2 links - one for displaying the page in English and another for Arabic. I want to modify it so that if the page is already in English, only the Arabic <a> tag will show, and vice versa if the page is in Arabic ...

Preventing Component Duplication in Vue.js: Tips to Avoid Displaying Two Instances on the Screen

After developing a Vue app in VS Code, I encountered an issue where the home component was rendered twice on the screen when attempting to run the application. Below is a screenshot of the resulting homepage: Here is the code from Home.vue: ...

What could be causing my header component to rerender even when there are no new props being received?

https://codesandbox.io/s/crimson-field-83hx6 In my project, I have a Header component that simply displays a fixed text and includes a console.log statement: const Header = props => { console.log("header render"); return ( <header> ...