Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @click in select options - Vue.js 2

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]);
}
like image 606
Natalia Avatar asked Sep 17 '17 02:09

Natalia


1 Answers

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).

like image 179
JiangangXiong Avatar answered Sep 19 '22 02:09

JiangangXiong