简体   繁体   中英

How can i use two methods in the same select v-model?

I have a select with two choices. Can i use one method for choice?

This is my select:

<select :value="selected" @change="sortAZ">
   <option disabled value="">Ordina per</option>
   <option>A-Z</option>
   <option>Z-A</option>
</select>

But with this selection I can only use the sortAZ method for each choice.

So, I have two methods: sortAZ and sortZA , I would like to use a method for the first option and a method for the second.

You can just store the currently selected value, and decide which method to call on onchange handler.

<select :v-model="selected" @change="sort" ">
   <option disabled value="">Ordina per</option>
   <option>A-Z </option>
   <option>Z-A</option>
</select>

methods:{
  sort(){
    if(selected == 'A-Z'){
      callSortAZ();
    }
    else if(selected == 'Z-A'){
      callSortZA();
    }
  }
}

I hope it helps.

Using v-model you can update the local variable selected value then read the value of selected from inside the method & do AtoZ or ZtoA sort.

 <template> <select v-model="selected" @change="handleSort" "> <option disabled value="">Ordina per</option> <option value="az">AZ </option> <option value="za">ZA</option> </select> </template> <script> new Vue({ el: '...', data: { selected: '' }, methods: { handleSort() { const selectedVal = this.selected; if (selectedVal === 'az') { // sort a to z, call other method ... } else if (selectedVal === 'za') { // sort z to a, call other method ... } else { ... } } } }) </script>

Use the v-model directive to bind the selected option value. Then check which value is selected in the change method.

 new Vue({ el: '#app', data: {selected:''}, methods: { sorter: function() { if (this.selected === 'A-Z') { // the logic for AZ sorting... console.log('AZ option selected') } else if (this.selected === 'Z-A') { // the logic for ZA sorting... console.log('ZA option selected') } } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <select v-model="selected" @change="sorter" > <option disabled value="">Ordina per</option> <option value='A-Z'>AZ</option> <option value='Z-A'>ZA</option> </select> </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