I'd like to use @click in select options.
So far I have:
<button @click="sortBy('name')">sort by name</button>
<button @click="sortBy('price')">sort by price</button>
and it works, however when I insert it into option tag, it stopped working.
<select name="sortBy" id="sortBy">
<option value="sort">sort By</option>
<option @click="sortBy('name')">name</option>
<option @click="sortBy('price')">price</option>
</select>
My function:
sortBy(sortKey) {
this.items.sort((a, b) =>
(typeof a[sortKey] === 'string' || typeof b[sortKey] === 'string') ?
a[sortKey].localeCompare(b[sortKey]) : a[sortKey] - b[sortKey]);
}
You can't bind event to <option>
, and you need to use the change
event of the <select>
, once you click a option, the change event callback of select
will be invoked:
<select name="sortBy" id="sortBy" @change="sortBy(sortType)" v-model="sortType">
<option v-for="item in sortOptions" :value="item.value">{{item.text}}</option>
</select>
new Vue({
el: '...',
data: {
sortType: 'sort',
sortOptions: [
{ text: 'sort by', value: 'sort' },
{ text: 'name', value: 'name' },
{ text: 'price', value: 'price' }
]
}
})
Once you change a option the value of sortTyoe
will be changed to it, and the @change will call the callback sortBy(sortType)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With