typescript - Vue välj alternativ baserat på villkor
Jag har följande mall för en rullgardinsmeny:
<select v-model="selectedClient" class="stat-select text-u-c">
<option disabled value="">Please select a Client</option>
<option>{{}}</option>
</select>
...och jag har en knapp click-hanterare som jag vill fylla <option>-elementen baserat på någon viss villkor:
if (Department == 'IT') {
// select option values should be A,B,C
} else (Department == 'Finance') {
// select option values should be X,Y,Z
}
Hur kan jag uppnå detta?
Svar #1
Du skulle använda Vues list-renderingssyntax med v-for:
<ELEMENT v-for="VARIABLE in ARRAY" :key="ITERATOR_ID">
I ditt fall med <option>s, skulle du ha något som detta:
<option v-for="item in options" :key="item.id">{{item.label}}</option>
...där options är en dataprototyp, som innehåller en array som denna:
[
{ id: 1, label: 'A' },
{ id: 2, label: 'B' },
{ id: 3, label: 'C' },
]
Om du vill ha en annan uppsättning <option> baserat på Department, kan du ställa in this.options till en annan array i enlighet med detta, och databindningen kommer att uppdatera <option> automatiskt:
methods: {
getOptions() {
const dept = this.Department;
if (dept === 'IT') {
this.options = [
{ id: 1, label: 'A' },
{ id: 2, label: 'B' },
{ id: 3, label: 'C' },
];
} else if (dept === 'Finance') {
this.options = [
{ id: 4, label: 'X' },
{ id: 5, label: 'Y' },
{ id: 6, label: 'Z' },
];
}
}
}
new Vue({
el: '#app',
data: () => ({
options: null,
Department: null,
selectedClient: null,
}),
methods: {
getOptions() {
this.selectedClient = null;
if (this.Department === 'IT') {
this.options = [
{ id: 1, label: 'A' },
{ id: 2, label: 'B' },
{ id: 3, label: 'C' },
];
} else if (this.Department === 'Finance') {
this.options = [
{ id: 4, label: 'X' },
{ id: 5, label: 'Y' },
{ id: 6, label: 'Z' },
];
}
}
},
})<script src="https://unpkg.com/[email "></script>
<div id="app">
<div>
<span>Department:</span>
<input id="dept" type="radio" v-model="Department" value="IT">
<label for="dept">IT</label>
<input id="fin" type="radio" v-model="Department" value="Finance">
<label for="fin">Finance</label>
<button @click="getOptions">Get options</button>
</div>
<select v-model="selectedClient" class="stat-select text-u-c">
<option disabled value="">Please select a Client</option>
<option v-for="item in options" :key="item.id">{{item.label}}</option>
</select>
{{selectedClient}}
</div>