2017-09-17 60 views
0

我想在选择选项中使用@click。在选择选项中使用@click - Vue.js 2

到目前为止,我有:

<button @click="sortBy('name')">sort by name</button> 
<button @click="sortBy('price')">sort by price</button> 

和它的作品,但是当我将其插入选项标签,它停止工作。

<select name="sortBy" id="sortBy"> 
    <option value="sort">sort By</option> 
    <option @click="sortBy('name')">name</option> 
    <option @click="sortBy('price')">price</option> 
</select> 

我的功能:

sortBy(sortKey) { 
    this.items.sort((a, b) => 
    (typeof a[sortKey] === 'string' || typeof b[sortKey] === 'string') ? 
    a[sortKey].localeCompare(b[sortKey]) : a[sortKey] - b[sortKey]); 
} 

回答

2

不能绑定事件<option>,你需要使用change事件<select>的,一旦你点击一个选项,而select变化事件回调将被调用:

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

一旦你改变一个选项的sortTyoe值将被改为它,并且@change将致电回拨sortBy(sortType)

+0

非常感谢! 还有一个问题:是否可以在每个选择选项上使用不同的功能? – Natalia

+0

您不能直接使用不同的函数,因为浏览器只支持将DOM事件绑定到'select',no'option'。 – JiangangXiong