【问题标题】:Vue.js multiple checkbox filterVue.js 多复选框过滤器
【发布时间】:2019-10-30 07:17:39
【问题描述】:

我做了两个 Vue.js 多复选框过滤器的例子:“工作”和“游戏”。

“工作”:https://jsfiddle.net/ostapenko25/cw7kyp83/
《游戏》:https://jsfiddle.net/ostapenko25/bu7hcvqg/

//“Jobs”
computed: {
 filteredJobs() {
  return this.jobs.filter(({ id, userId }) => {
    return (
      (this.checkedUserIds.length === 0 ||
        this.checkedUserIds.includes(userId)) &&
      (this.checkedIds.length === 0 || this.checkedIds.includes(id))
    );
  });
 }
}

//“Games”   
computed: {
 filteredGames() {
   return this.games.filter(({ game_id, season }) => {
     return (
       (this.checkedseasons.length === 0 ||
         this.checkedseasons.includes(season)) &&
          (this.checkedgame_ids.length === 0 || this.checkedgame_ids.includes(game_id))
        );
     });
   }    
}

除了 JSON 数据以及键和属性的名称之外,它们完全相同。但是第一个示例有效,而第二个示例无效:当我尝试使用复选框时,游戏列表变为空。请帮我找出是我在“游戏”示例中的错误。

【问题讨论】:

    标签: vue.js filtering


    【解决方案1】:

    问题在于您的数据源 JSON 提要使用 strings,而您的过滤逻辑使用 numbers

    基本上,您会被绊倒,因为includes 使用Same-value-zero equality 算法,该算法在比较值时不会在类型之间进行强制转换。这意味着,如果您使用 数字 201720182019 填充视图的季节过滤器,但您过滤的数据将季节表示为 字符串作为"2017",这意味着[2017].includes("2017") 的计算结果为false,因为2017 !== "2017" evaluates tofalse`。

    在您的过滤器中使用相同的类型,就像您的数据使用的一样,就像在中一样

    data() {
      return {
          games: [],
          seasons: ["2016", "2017", "2018"],
          // etc..
      };
    }
    

    或者通过在过滤逻辑中转换字符串和数字来解释类型的差异,如

    computed: {
      filteredGames() {
          return this.games.filter(({ game_id, season }) => {
              const seasonNumber = Number(season);
              return (
                (this.checkedseasons.length === 0 ||
                  this.checkedseasons.includes(seasonNumber)) &&
                (this.checkedgame_ids.length === 0 || this.checkedgame_ids.includes(game_id))
              );
            });
          }    
      }
    

    工作示例:

    使用相同的类型:https://jsfiddle.net/p5e48w9c/1/

    转换为同构类型:https://jsfiddle.net/dx1usgch/1/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-04
      • 2011-09-25
      • 2016-10-01
      • 1970-01-01
      相关资源
      最近更新 更多