【问题标题】:reseting filter if "All" is selected Vuejs如果选择“全部”,则重置过滤器 Vue Js
【发布时间】:2020-12-07 05:14:08
【问题描述】:

我有这个对象数组:

obj=
[{name: 'joe', job: 'teacher', city: 'miami'},
{name: 'bill', job: 'police', city: 'yorkshire'},
{name: 'sarah', job: 'driver', city: 'michigan'}]

我有一个下拉菜单,其中包含如下选项:

<select v-model="selected">
  <option>blue</option>
  <option>green</option>
  <option>black</option>
  <option>all</option>
</select>

然后如果其中一个被选中,我会将它们与数组中的一个对象相关联:

if (selected === "blue") {
  optionSelected = 'joe'
} else if (selected === "green") {
  optionSelected = 'bill'
} else if (selected === "black") {
  optionSelected = 'sarah'
} else if (selected === "all") {
  // what should go here?
}

然后我像这样过滤它:

obj = obj.filter(object => object.name === optionSelected)

所以现在如果我选择blue 我的obj 变成{name: 'bill', job: 'police', city: 'yorkshire'} 等等,这很好。但是我不知道如何过滤all。因此,当它被选中时,obj 会重置为包含所有值,例如:

obj=
[{name: 'joe', job: 'teacher', city: 'miami'},
{name: 'bill', job: 'police', city: 'yorkshire'},
{name: 'sarah', job: 'driver', city: 'michigan'}]

我该怎么做?

请注意: 代码的架构是这样设置的,我无法更改。

【问题讨论】:

    标签: javascript arrays vue.js select filter


    【解决方案1】:

    我将从一个将颜色映射到名称的对象开始,这样您就可以避免所有 if..else if 的东西

    const colorNameMap = {
      blue: 'joe',
      green: 'bill',
      black: 'sarah',
      all: false // totally optional since undefined is falsy
    }
    

    然后您只需检查所选颜色是否与地图中的某些内容匹配。如果没有,只需返回整个obj

    const name = colorNameMap[this.selected]
    const filtered = name ? obj.filter(o => o.name === name) : obj
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-18
      • 2013-04-05
      • 2013-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多