简体   繁体   中英

Vue select options based on condition

I have the following template for a dropdown:

<select v-model="selectedClient" class="stat-select text-u-c">
  <option disabled value="">Please select a Client</option>
  <option>{{}}</option>
</select>

...and I have a button click -handler that I want to populate the <option> s based on some condition:

if (Department == 'IT') {
  // select option values should be A,B,C
} else (Department == 'Finance') {
  // select option values should be X,Y,Z
}

How can I accomplish this?

You would use Vue's list rendering syntax with v-for :

<ELEMENT v-for="VARIABLE in ARRAY" :key="ITERATOR_ID">

In your case with <option> s, you would have something like this:

<option v-for="item in options" :key="item.id">{{item.label}}</option>

...where options is a data property, containing an array like this:

[
  { id: 1, label: 'A' },
  { id: 2, label: 'B' },
  { id: 3, label: 'C' },
]

If you want a different set of <option> s based on Department , you could set this.options to a different array accordingly, and the data binding will update the <option> s automatically:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM