2017-09-17 26 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

相關問題