Reputation: 6276
I have two select fields in Vue 2. Both have common values as company name records. I'm using the vue-select
component to build a select like this:
<v-select :options="companyOptions" v-model="company_name"></v-select>
and for the other select like this:
<v-select multiple :options="companyOptions" v-model="selectedCompanies"></v-select>
I have a computed value like this:
companyOptions() {
if(this.model.data)
{
return this.model.data.map(d => ({label: d.name, value: d.id}))
}
},
Model data is populated via axios.
Now if any body selects an item in the first select then it should remove the value from the options for the second select. Can someone guide me? The problem I think I'm facing is if someone selects an item in the first select then the company can be removed from the second select by slicing the array, but if someone then selects a different item in the first select I want the original list of options; I mean it should add the previously removed value back and remove the newly selected value.
Upvotes: 2
Views: 2114
Reputation: 82439
Filter your list before you map it.
companyOptions() {
if(this.model.data)
{
return this.model.data
.map(d => ({label: d.name, value: d.id}))
}
},
filteredCompanyOptions() {
if (this.model.data)
{
return this.model.data
.filter(f => f.name !== this.company_name.label)
.map(d => ({label: d.name, value: d.id}))
}
}
And in your template
<v-select multiple :options="filteredCompanyOptions" v-model="selectedCompanies"></v-select>
Note: you will have to handle the case where someone selects an option in the first select, then selects options in the second select, then picks an option in the first select that was selected in the second select. Possibly by clearing selectedCompanies
whenever company_name
changes. Here is how you might do that.
watch:{
company_name(newValue){
if (!this.selectedCompanies.length > 0){
return
}
const index = this.selectedCompanies.findIndex(v => v.value == newValue.value)
if (index >= 0)
this.selectedCompanies.splice(index, 1)
}
}
Upvotes: 2