【问题标题】:using `filterBy` with dynamic select list使用带有动态选择列表的`filterBy`
【发布时间】:2016-07-07 18:20:25
【问题描述】:

我正在使用vue.js 构建一个包含一长串选定项目的表单。我正在使用此处记录的动态选择列表:http://012.vuejs.org/guide/forms.html#Dynamic_Select_Options

但是,我希望允许用户使用 filterBy 指令快速过滤此列表。我看不出如何将这两者结合起来——是否可以过滤动态列表?或者filterBy 是否只能用于v-for

【问题讨论】:

  • 你还在使用 0.12 吗?在 1.0 指南中,动态选择列表的示例使用 v-for vuejs.org/guide/forms.html#Select
  • @asemahle-- 我可以使用v-for,但我想使用动态选择,以便创建optgroups。问题是我是否可以将filterBy 与动态选择一起使用而不是v-for

标签: javascript vue.js multi-select


【解决方案1】:

在 0.12 中,您可以使用带有选项参数的过滤器。 docs 显示的语法看起来与过滤 v-for 相同。

这是一个显示 filterBy 的示例(使用版本 0.12.16):

var app = new Vue({
  el: '#app',
  
  data: {
    selected: '',
    options: [
      { text: '1', value: 1, show: true },
      { text: '2', value: 2, show: false },
      { text: '3', value: 3, show: true },
      { text: '4', value: 4, show: true },
      { text: '5', value: 5, show: false },
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.16/vue.js"></script>
<div id="app">
  Filter by 'show' <br>
  <select v-model="selected" options="options | filterBy true in 'show'"></select>
</div>

注意:&lt;select v-model&gt;options 参数一直是 deprecated in 1.0。在 1.0 中,您可以直接在 &lt;select&gt; 中使用 v-forv-for 可以嵌套使用 optgroups。

【讨论】:

    【解决方案2】:

    检查这个小提琴https://jsfiddle.net/tronsfey/4zz6zrxv/5/

    <div id="app">
       <input type="text" v-model="keyword">
       <select name="test" id="test">
         <optgroup v-for="group in list | myfilter keyword" label="{{group.label}}">
           <option value="{{item.price}}" v-for="item in group.data">{{item.text}}</option>
         </optgroup>
       </select>
    </div>
    
    
    
    
     <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.js"></script>
        new Vue({
            el: '#app',
            data: function () {
                return {
                        keyword : '',
                    list: [
                      {
                        label:'A',
                        data:[
                           {price: 3, text: 'aa'},
                           {price: 2, text: 'bb'}
                        ]
                      },
                        {
                        label:'B',
                        data:[
                           {price: 5, text: 'cc'},
                           {price: 6, text: 'dd'}
                        ]
                      }
                    ]
                }
            },
            filters : {
                myfilter : function(value,keyword){
                return (!keyword || keyword === 'aaa') ? value : '';
              }
    
            }
        })
    

    您可以使用 v-for 创建 optgroup,然后使用 filterBy 或自定义过滤器(如小提琴中所示)来过滤您的选项数据。

    希望它会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2020-05-24
      • 2023-04-11
      • 2020-10-16
      相关资源
      最近更新 更多