v-show 嵌套数组项是否匹配过滤后的数组

v-show if nested array items match filtered array

我必须编写一个 Vue webapp,它将采用多个过滤器,将它们推送到一个数组,然后在单击方法上检查过滤器数组值,以及是否有任何值与嵌套图块内的任何嵌套值匹配数组,显示匹配的方块。所以,我的过滤器数组可能有:

filters: ['cookies', 'jogging']

我的嵌套图块数组将包含:

tiles: [
 {
  "name": "Greg",
  "food": ["cookies", "chips", "burgers"],
  "activities": ["drawing", "watching movies"]
  "favourite places": ["the parks", "movie theatre"]
 },{
  "name": "Robyn",
  "food": ["cookies", "hotdogs", "fish"],
  "activities": ["reading", "jogging"]
  "favourite places": ["beach", "theme parks"]
 },{
  "name": "John",
  "food": ["sushi", "candy", "fruit"],
  "activities": ["writing", "planning"]
  "favourite places": ["the moon", "venus"]
 }
]

在上面的示例中,将显示的图块是 Robyn,因为她喜欢吃饼干和慢跑。

到目前为止,我的想法是编写一个 for 循环来检查嵌套数组中的值,这是我从这个解决方案中得到的:

但是我无法建立连接,只是显示 v-for/v-show 中的项目。我已经掌握了将所有过滤器推送到过滤器数组的方法,但是当涉及到将它与嵌套数组匹配并根据匹配显示它们时,我不知所措。最好我想用 vanilla js (es5) 写出来。

感谢任何帮助。

谢谢!

computed: {
  fullyMatchedTiles () {
    // Matches must contain all terms from filter array

    return this.tiles.filter(obj=> {

      // Filter the filters to get matched count
      let matchedFilters = this.filters.filter(filterItem=> {

        // Check each property by looping keys
        for (key in obj) {

          // Only evaluate if property is an array
          if (Array.isArray(obj[key])) {

            // Return true if filterItem found in obj
            if (obj[key].some(r=> filterItem.indexOf(r) >= 0)) {
              return true
            }
          }
        }
      })
      return this.filters.length === matchedFilters.length
    }) 
  },

  partiallyMatchedTiles () {
    // Matches must contain at least one term from filter array
    // Check each object in the array
    return this.tiles.filter(obj=> {

      // Check each property by looping keys
      for (key in obj) {

        // Only evaluate if property is an array
        if (Array.isArray(obj[key])) {

          // Return true to the filter function if matched, otherwise keep looping
          if (obj[key].some(r=> this.filters.indexOf(r) >= 0)) {
            return true
          }
        }
      }
    })
  },
},

抱歉,这不是 es5。我太喜欢新功能了,不能花时间回到 5 年前。

有关显示在 vue 中返回的过滤对象的完整示例,请查看此代码笔 https://codepen.io/shanemgrey/pen/jOErWbe

我认为您描述的是在 v-for 中进行过滤。尝试使用 v-for 中可用的过滤来完成它似乎逻辑太复杂了。

我会按照所示的方式进行操作,方法是在新计算的 属性 中分解数组,然后根据需要在模板中使用生成的过滤数组。