【问题标题】:How to filter a list in VueJS with multiple watchers如何在具有多个观察者的 VueJS 中过滤列表
【发布时间】:2017-08-23 14:37:14
【问题描述】:

这是我第一次使用 VueJS。我正在尝试构建一个页面,该页面在右侧显示数据并在左侧有几个控件(复选框、下拉菜单、输入文本)。选择/输入左侧的控件时,右侧的数据将被过滤。

我正在尝试用虚拟数据在 JSBin 上为此准备一个小演示:http://jsbin.com/qujaraf/edit?html,js,console,output

我有一些数据,我有两个观察者codesearchtypesearch

问题

  1. 我希望在我输入内容时过滤列表。
  2. 我怎样才能做到这一点,以便在两个观察者中输入数据时,过滤器会考虑两个输入。例如,在这个演示中,如果用户在type 中输入actor 并在code 中输入three,那么应该只显示一个列表项。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    http://jsbin.com/huteyasuto/1/edit?html,js,console,output

    data: {
         typesearch: '',
         codesearch: '',
         processingmsg: 'waiting for you...',
         items: [
           {name: 'Stackoverflow', type: 'development', code: "one"},
           {name: 'Game of Thrones', type: 'serie', code: "two"},
           {name: 'Jon Snow', type: 'actor', code: "three"}
         ],
        filteredItems: [
           {name: 'Stackoverflow', type: 'development', code: "one"},
           {name: 'Game of Thrones', type: 'serie', code: "two"},
           {name: 'Jon Snow', type: 'actor', code: "three"}
         ]
      },
    
      // trigger filter on either input
      watch: {
        typesearch: function () {
          this.processingmsg = "processing type...";
          this.filteredItems = this.filterItems()
        },
        codesearch: function () {
          this.processingmsg = "processing code...";
          this.filteredItems = this.filterItems()
        }
      },
    
      // filter the list based on typesearch, then on codesearch               
      methods: {
        filterItems: function() {
          return this.items.filter(item => {
             return (
               (item.type.indexOf(this.typesearch.toLowerCase()) > -1)
             );
          }).filter(item => {
            return (item.code.indexOf(this.codesearch.toLowerCase()) > -1)
          })
        }
      }  
    

    标记更改:

    <div v-for="item in filteredItems" >
      <p>{{item.name}}<p>
    </div>
    

    【讨论】:

    • 感谢这项工作。我试图理解它。您制作了两份数据副本(itemsfilteredItems)是否有原因?
    • 我不知道如何在数据声明中引用原始副本,否则我会。如果您不复制,您最初将有一个空列表,因为该视图现在引用过滤后的列表。在现实世界中,无论如何您都不会使用数组字面量,因此两个列表都会引用表示数据的变量。
    • 是的,在现实世界中,我的数据将作为 API 调用来自服务器。那么在这种情况下,这可以正常工作吗?
    • 这是一个非常简单的实现。我不会完全将其用于生产,但这对学习很有好处。
    • 使用计算将是更好的方法。
    猜你喜欢
    • 1970-01-01
    • 2019-04-22
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 2019-03-09
    相关资源
    最近更新 更多