Good day! I am new in Vuejs. Please help me. I want to disable the select option after I select and set the select to default value. for example
<select name="recipient" @change="changeFunc($event)">
<option>--Select--</option>
<option v-for="recipient in recipients" :key="recipient.id" :value="recipient.id" :disabled="recipient.disabled">{{ recipient.name }}</option>
</select>
export default {
data: function() {
return {
recipients: [
{'id':3, 'name':'aaa'},
{'id':5, 'name':'bbb'},
{'id':8, 'name':'ccc'}
],
}
},
method: {
changeFunc(e) {
//TODO disable the select value and set to default value
}
}
}
Please help how to do it. Thank you.
CodePudding user response:
Try the following code
<select name="recipient" v-model="selected" @change="changeFunc($event)">
<option>--Select--</option>
<option v-for="recipient in recipients" :key="recipient.id" :value="recipient.id" :disabled="recipient.disabled">{{ recipient.name }}</option>
</select>
export default {
data: function() {
return {
selected: {},
recipients: [
{'id':3, 'name':'aaa', 'disabled': false},
{'id':5, 'name':'bbb', 'disabled': false},
{'id':8, 'name':'ccc', 'disabled': false}
],
}
},
method: {
changeFunc(e) {
const index = this.recepients.findIndex((el) =>{
if(el.id == this.selected){
return true;
}
});
if(index){
this.recepeints[index].disabled = true;
this.selected = "";
}
}
}
}
The changeFunc() find index of selected value and set disabled to true and reset selected value
CodePudding user response:
You can achieve this with a simple approach by iterating the input array on option change.
this.recipients.forEach(obj => {
obj['disabled'] = (obj.id === this.recipient)
});
Live Demo :
new Vue({
el: '#app',
data: {
recipient: '',
recipients: [
{'id':3, 'name':'aaa'},
{'id':5, 'name':'bbb'},
{'id':8, 'name':'ccc'}
]
},
methods: {
changeFunc() {
this.recipients.forEach(obj => {
obj['disabled'] = (obj.id === this.recipient)
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<select v-model="recipient" @change="changeFunc">
<option value="">--Select--</option>
<option v-for="recipient in recipients" :key="recipient.id" :value="recipient.id" :disabled="recipient.disabled">{{ recipient.name }}</option>
</select>
</div>