javascript 在选择选项中使用 @click - Vue.js 2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46260052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:33:03  来源:igfitidea点击:

Using @click in select options - Vue.js 2

javascriptvuejs2

提问by Natalia

I'd like to use @click in select options.

我想在选择选项中使用@click。

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

回答by JiangangXiong

You can't bind event to <option>, and you need to use the changeevent of the <select>, once you click a option, the change event callback of selectwill be invoked:

您不能将事件绑定到<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' }
       ]
    }
})

Once you change a option the value of sortTyoewill be changed to it, and the @change will call the callback sortBy(sortType).

一旦你改变了一个选项,它的值sortTyoe就会改变,@change 将调用回调sortBy(sortType)