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

Manipulating variables across various methods in TypeScript

I have a simple code snippet where two variables are defined in the Main method and I need to access them from another method. However, I am encountering an issue with 'variables are not defined', even though I specified them in the declerations ...

Making a REST call with values containing an apostrophe

Currently, I am utilizing REST and ajax to retrieve data from SharePoint using the URL below: https:xxxxxxxx/_vti_bin/ListData.svc/RMSD_Tasks?$orderby=IssueValue asc,StatusValue desc&$filter="+dropValue+" eq '"+secondFilterVal+"'&groupby ...

Unit Testing in Aurelia: Creating a Mock for a Custom Resolver

Below is the snippet of code that I am currently trying to test: import {inject} from 'aurelia-framework'; import {CrudResource, DependencyFactory} from 'utils'; let commonData = {}; @inject(DependencyFactory.of(CrudResource)) ...

Tests using Cypress for end-to-end testing are failing to execute in continuous integration mode on gitlab.com

Challenges with Setting Up Cypress in Gitlab CI We have been facing difficulties setting up Cypress in the CI runners of gitlab.com using the default blueprint from vue-cli to scaffold the project. Despite trying various configurations in the gitlab.yml f ...

Utilizing Multiple Components on a Single Page in React.js

I'm currently setting up a React main page that renders two separate components - Header and Test. render() { return ( <Header /> <Test /> ); } The Header component contains static content, while the ...

Having trouble retrieving the default selected value using the index in Angular Material's mat-button-toggle functionality

I'm encountering an issue with setting the default value for a toggle button group. The code is simple and the toggle buttons are correctly fetching values from the index, but I can't seem to get one of them to be default selected. I tried settin ...

Obtain an Element Using Puppeteer

Currently grappling with a sensitive issue concerning puppeteer. The HTML structure in question is as follows: <tbody> <tr rel="0" class="disabled" id="user6335934" class="odd"> ...

Ajax calls for validations are failing to trigger a response from PHP

I am currently working on validating my signup form using PHP and AJAX, but unfortunately, I am not receiving any response value. Below is the AJAX code snippet I am using: <script type="text/JavaScript"> function frmValidation(str) { ...

"Optimize your website by incorporating lazy loading for images with IntersectionObserver for enhanced performance

How can I use the Intersection Observer to load an H2 tag only when the image is visible on the page? Here is the JavaScript code I currently have: const images = document.querySelectorAll('img[data-src]'); const observer = new IntersectionObser ...

Having trouble with loading JSON due to a Cross-Domain AJAX problem

I am facing a challenge with a URL that I do not have control over, which returns a JSON string. Within this JSON string, there is a URL that I am attempting to load using JavaScript/jQuery AJAX. However, I am encountering a Cross-Domain issue while trying ...

Is it possible to use require() to read a .json file from a dependent library?

Is it possible to access a .json file within one of my dependent libraries? I'm hesitant to use fs to read ./node_modules/somelib/properties.json because the library could have been installed globally. Is there a way to achieve this using require in ...

Break apart the string and transform each element in the array into a number or string using a more specific type inference

I am currently working on a function that has the ability to split a string using a specified separator and then convert the values in the resulting array to either strings or numbers based on the value of the convertTo property. Even when I call this fun ...

The input box fails to show larger values on the user's page

Show me the biggest number that the user enters in an input box and then display it back to them. I need some improvements to my code, ideally making it possible with just one input box instead of two. <!DOCTYPE html> <html la ...

The Typescript SyntaxError occurs when attempting to use an import statement outside of a module, typically within a separate file that contains

I am currently developing a Minecraft bot using the mineflayer library from GitHub. To make my code more organized and reusable, I decided to switch to TypeScript and ensure readability in my project structure (see image here: https://i.stack.imgur.com/znX ...

Deploying CSS/JS files in Magento 2 is a crucial

Hello, I recently set up magento2 with the sample data included. After attempting to deploy static css/JS using the command php bin/magento setup:static-content:deploy, I didn't receive any errors but the issue persists. Additionally, I am unable to l ...

Guide to utilizing a ref in multiple components within Vuejs

I'm currently working on a project that involves two components (Title and Input components) with the same title reference. The requirement is for changes made to one component to reflect in the other as well. I attempted to implement suggestions from ...

Using JQuery to enhance the functionality of ajax-loaded content

Having difficulty implementing a more/less functionality in an ajax-loaded section of a webpage. I customized a script found at http://jsfiddle.net/gDvyR/72/, primarily by adding "on" functionality to address the ajax issue. You can view the modified ver ...

Tips for enhancing the efficiency of my JavaScript code?

On my page, I have a list of items with various actions assigned to them. One can either click on an icon next to each item or check a checkbox on the left side. However, when clicking on an action after selecting multiple items, there is a noticeable lag ...

There seems to be an issue with the Webpack command as it is unable to locate the module 'webpack'

Currently, I am in the process of developing a web application using Vue.js for the frontend. To work with Vue.js, webpack is required and has been installed globally on my system. However, whenever I attempt to execute the 'webpack' command, an ...

What is the best way to restore a component's state to its default settings when it receives new props?

I have a Next.js project in development with a custom Layout already set up. I want the header component to reset whenever a new page is navigated to, so that the menu reverts back to its default state. Does anyone know how I can achieve this? import { F ...