14

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]);
}

1 Answer 1

22

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! One more question: is it possible to use different functions on each select option?
You can't use different functions directly, because the browser only support bind the DOM event to select, no option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.