[英]Vue select options based on condition
我有以下下拉模板:
<select v-model="selectedClient" class="stat-select text-u-c">
<option disabled value="">Please select a Client</option>
<option>{{}}</option>
</select>
...并且我有一个按钮click
处理程序,我想根据某些条件填充<option>
s:
if (Department == 'IT') {
// select option values should be A,B,C
} else (Department == 'Finance') {
// select option values should be X,Y,Z
}
我怎样才能做到这一点?
您可以将 Vue 的列表渲染语法与v-for
一起使用:
<ELEMENT v-for="VARIABLE in ARRAY" :key="ITERATOR_ID">
在您使用<option>
的情况下,您将拥有以下内容:
<option v-for="item in options" :key="item.id">{{item.label}}</option>
...其中options
是一个数据属性,包含这样的数组:
[
{ id: 1, label: 'A' },
{ id: 2, label: 'B' },
{ id: 3, label: 'C' },
]
如果您想要基于Department
的一组不同的<option>
,您可以相应地将this.options
设置为不同的数组,并且数据绑定将自动更新<option>
:
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/vue@2.5.17"></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-uc"> <option disabled value="">Please select a Client</option> <option v-for="item in options" :key="item.id">{{item.label}}</option> </select> {{selectedClient}} </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.