在Vue 3中的多个选择组件中选择互斥选项

VUE组件的options变量有5个唯一值。我想让用户为我给出的每个选择选项只选择1个值。即我有5个输入select组件,我希望用户在每个组件中只选择一个无法被其他select组件使用的值。

例如

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 ] 

如果用户在输入1中选择橙色,则用户无法在输入2到5中再次选择橙色。

我已尝试通过维护itemSelected[]和itemsAvailable[]来创建2个数组,但无法解决此问题。

如何在Vue 3中解决此问题?


解决方案

您可以创建组件以供选择,并将需要的值作为参数传递:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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/vue@3.2.29/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>

相关文章