Home > front end >  Selecting mutually exclusive options among multiple select components in Vue 3
Selecting mutually exclusive options among multiple select components in Vue 3

Time:03-08

There are 5 unique values to the options variable to the vue component. I would like the user to chose only 1 value for every select options I give. i.e. I have 5 input select components, I want the user to select just 1 value in each component which cannot by used by other select component.

For e.g.

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

If user selects orange in input one, the user cannot select orange again in inputs 2 to 5.

I have tried creating 2 arrays by maintaining itemSelected[] and itemsAvailable[], however I am unable to solve the issue.

How do I solve this issue in Vue 3?

CodePudding user response:

You can create component for selection, and pass needed values as params:

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/[email protected]/dist/vue.global.prod.js"></script>
<div id="demo">
  <div >
    <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>

  • Related