Choosing between exclusive choices across multiple selection elements in Vue 3

In my Vue component, there are 5 distinct values stored in the options variable. I want users to select only one value from each of the 5 select options I provide. This means that once a user selects a value in one input select component, that same value cannot be chosen in any of the other components.

For example:

input one: [ orange, green, yellow, black, blue ] 
input two: [ orange, green, yellow, black, blue ] 
input three: [ orange, green, yellow, black, blue ] 
input four: [ orange, green, yellow, black, blue ] 
input five: [ orange, green, yellow, black, blue ] 

If a user selects "orange" in input one, they cannot select "orange" again in inputs 2 through 5.

I have attempted to address this by creating arrays to track selected items and available items, but I am struggling to find a solution.

How can I resolve this issue in Vue 3?

Answer №1

To efficiently handle selection in Vue, you can create a component and pass necessary parameters to it:

const { ref, computed, watch } = Vue
const app = Vue.createApp({
  setup() {
    const items = ref(['orange', 'green', 'yellow', 'blue', 'purple'])
    const getItems = computed(() => 
      items.value.filter(i => !selected.value.includes(i))
    )
    
    const selected = ref([])
    const getSelected = (val) => { 
      if(!selected.value.includes(val)) selected.value.push(val) 
    }
    
    const reseted = ref(false)
    const reset = () => {
      selected.value = []
      reseted.value = true
    }
    
    return { items, selected, getSelected, getItems, reset, reseted }
  }
})
app.component('selComp', {
  template: `
    <div :style="{color: selected}">Selected {{ idx + 1 }}: {{ selected }}</div>
    <select v-model="selected" @change="setSelected($event)">
      <option disabled value="">Please select one</option>
      <option v-for="item in items" :key="item">{{ item }}</option>
    </select>
  `,
  props: ['items', 'idx', 'reseted'],
  setup(props, { emit }) {
    const selected = ref(null)
    const setSelected = (e) => { emit('select', e.target.value) }
    
    watch(() => props.reseted, () => {
      selected.value = null
      emit('cleared')
    })
    
    return { selected, setSelected }
  }
})
app.mount('#demo')
.cont{
  display: flex;
  flex-wrap: wrap;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e5939080a5d6cbd7cbd7dc">[email protected]</a>/dist/vue.global.prod.js"></script>
<div id="demo">
  <div class="cont">
    <div v-for="(item, i) in items.length" :key="i">
      <sel-comp :items="getItems" :idx="i" :reseted="reseted" 
        @select="getSelected" @cleared="reseted=false">
      </sel-comp>
    </div>
  </div>
  <p>{{ selected }}</p>
  <button @click="reset">Reset</button>
</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

React Material-UI Multiple Select with Checkboxes not displaying initial selections as checked

I am fairly new to working with React and MUI, so please bear with me. Currently, I am in the process of learning how to create Multiple Select Options with checkboxes by populating the Dropdown Options from an Array. Although I have set up the initial/de ...

Unusual occurrences when using `mapply` in R

I find myself getting confused when using mapply, but I can't figure out where I'm going wrong. I'm attempting to categorize multiple groups based on specific cutoff values for each group... > dt <- source("https://pastebin.com/ra ...

What results can be expected from a piped file stream?

Perhaps the wording of the question may not be perfect, but here is some additional context. With GridFSBucket, I am able to store a file in MongoDB and retrieve a download stream for that file. Here's my query: If I wanted to send that file back as a ...

What could be causing the shake effect on the MUI dialog to not work when clicking away?

I am trying to implement a shake effect when the user clicks outside the MUI dialog to indicate that clicking away is not allowed. However, the code I have so far does not seem to be working as the effect is not being applied. Can someone please help me ...

What sets Joomla file inclusion apart from the rest?

Can someone please explain the difference between including a JavaScript script file in the following two ways? I created this within a system plugin in Joomla and included the JavaScript file inside the "onAfterInitialise" function. 1) <script type ...

Fetching data in a post request seems to be causing an issue with FormData image being

I've implemented a profile picture file upload system with the following HTML: <form enctype="multipart/form-data" id="imageUpload" > <img id="profileImage" src="./images/avatar.png& ...

What are some effective design principles for creating REST APIs in expressjs?

To streamline my code organization, I made the decision to create a methods folder. Within this folder, I store individual JavaScript files for each URL endpoint (such as website.com/billings). //expressJS configuration... const billings = require('. ...

What is the best way to incorporate a Json file into a JavaScript file?

Using JSON data in JavaScript I recently wrote a JavaScript program that selects a random "advice number" between 1 and 50. Now, I need to figure out how to access a JSON file for the advice messages. JavaScript file: Advice_number = Math.floor(Math.ran ...

To obtain the desired response, I must make an additional GET request

Upon sending the first GET request to this endpoint, I receive a response of allEvents = []. However, if I wait a few seconds and hit the endpoint again, I get the desired results with a populated allEvents array. It seems that the function is not executin ...

What could be causing my table to appear multiple times in the HTML when using jQuery?

Using Jquery to dynamically return a list of products, render it as HTML, and show it on the page using $(selector).html(html), I've encountered an issue. When adding products to the cart too quickly, which triggers the rendering of the cart again, th ...

Transforming Several Dropdowns using jQuery, JSON, and PHP

Hey there! I'm looking to update the state depending on the country and city based on the chosen state. <label>Country:</label><br/> <select onchange="getval(this)"> <option value="">Select Country</op ...

Encountering a "Module not found" error while trying to run npm start in a Create React App

I'm attempting to initiate a React project using create-react-app. Encountered an error when running npm start: Failed to compile. multi ./node_modules/react-scripts/config/polyfills.js ./node_modules/react-dev-utils/webpackHotDevClient.js ./src/i ...

Unable to display select options in Laravel blade due to Vue.js v-for issue

It is expected that the result will display the value of the id <select class="form-control" name="uploaded_segment_id" id="uploaded_segment_id" required=""> <option value="">Choose Segment</option> <option v- ...

IE encounters issues making Ajax calls when transitioning from secure HTTPS requests to insecure HTTP requests

I am currently facing an issue with my ajax CORS request. It is functioning perfectly on all browsers except for Internet Explorer. In IE, the request doesn't even attempt to go through and fails instantly without any error messages appearing in the c ...

Incorporate pictures from the popup onto the main page

I have developed a basic PHP image editor script where users can select images from galleries and merge them together. However, I am facing an issue: The galleries open in a popup while the editor area is on the parent page. I am looking for a JavaScript ...

Angular binding causing decimal inaccuracies

Within my $scope, I have a variable tobing that can be either 2.00 or 2.20, and I am binding it to: <span>{{datasource.tobind}}</span> I want the displayed text to always show "2.00" or "2.20" with the two last digits, but Angular seems to au ...

Tips for integrating JavaScript code into React JS applications

I am attempting to create a scrollable table that scrolls both horizontally and vertically, using the example provided by . In my project directory under src/components/ScrollExample.js, I have copied and pasted the HTML code. In addition, in src/styles/c ...

"Using PHP to encode an array into JSON format might result in additional

My PHP array needs to be printed as clean JSON, but I'm encountering issues with extra quotes. While the current JSON output is technically valid, it's not formatted how I want it to be. Below you can see the original PHP array, the json_encode o ...

What is the best method for showcasing the parsed JSON data in a list view?

Hello, I am new to Android and seeking some guidance. I have two buttons - one for getting JSON data and the other for parsing it. While the first button is working fine, the second one doesn't display the list view as expected. I specifically want t ...

Efficient method for handling numerous AJAX requests

I have a web application that currently makes 14-15 AJAX calls to various APIs. The issue is that the combined time it takes for all the AJAX calls to complete is significantly longer than when I individually type each API's URL into the browser. Cur ...