【问题标题】:Vue.js - Resetting the filterBy resultsVue.js - 重置 filterBy 结果
【发布时间】:2016-07-26 22:38:40
【问题描述】:

https://jsfiddle.net/72tnpa0o/

<div id="filter-by-example">
  <label>Cool</label><input type="checkbox" v-model="cool">
  <label>notCool</label><input type="checkbox" v-model="notCool">
  <ul>
    <li v-for="user in users | filterBy cool in 'cool' | filterBy notCool in 'notCool'">
      {{ user.name }}
    </li>
  </ul>
</div>`



new Vue({
  el: '#filter-by-example',
  data: {
    name: '',
    users: [
      { 
        name: 'Bruce',
        cool: true,
        notCool: false
      },
      { 
        name: 'Chuck',
        cool: false,
                notCool: true
      },
      { 
        name: 'Jackie',
        cool: true,
        notCool: false
      }
    ]
  }
})

我在上面的小提琴链接上有一个例子。我可以通过输入复选框进行排序,但取消选中过滤器不会重置为原始结果。

有谁知道取消选中过滤器按钮后如何渲染整个数组?

【问题讨论】:

  • 试试 ALfredo EM 的答案。它完美地工作。 jsfiddle.net/72tnpa0o/4
  • Alfredo 解决方案的问题在于它忽略了您的代码有错误的事实。 coolnotCool 应该在组件中预先定义。在浏览器中打开控制台并更改复选框:您会看到 Vue 警告像疯了一样触发。

标签: javascript arrays vue.js


【解决方案1】:

这里的主要问题是选择器的逻辑是错误的:就目前而言,如果您取消选中这两个复选框,您将获得coolnotCool 的项目。它在开始工作的原因是因为你的代码中有一个错误(打开控制台,你会在那里看到错误):coolnotCool 在开头都是undefined

所以首先你需要概述你想要什么。完成此操作后,您可以使用函数进行过滤,而不是使用开箱即用的函数,如下所示:

<li v-for="user in users | filterBy filterCool">
  {{ user.name }}
</li>

filterCool 应该是这样的:

filterCool: function (element, i, list) {
  if (this.showCool && element.cool) return true;
  if (this.showNotCool && element.notCool) return true;
  if (!this.showNotCool && !this.showCool) return true;
  return false;
}

目前还不是一个完美的解决方案,但却是一个很好的开始。检查这个:https://jsfiddle.net/72tnpa0o/5/

【讨论】:

    【解决方案2】:

    如果 :false-value 复选框为空,则过滤器不适用

    尝试改变这个:

    <input type="checkbox" v-model="cool">
    <input type="checkbox" v-model="notCool">
    

    通过

    <input type="checkbox" :false-value="" v-model="cool">
    <input type="checkbox" :false-value="" v-model="notCool">
    

    【讨论】:

    • 您能进一步解释一下这背后的原因吗?我有一种感觉,即使它有效,它也是一个 hacky 解决方案。
    • 这个解决方案确实有效。谢谢阿尔弗雷多!但是,就像赫克托所问的那样,谁能进一步解释这是如何工作的?
    【解决方案3】:

    还要确保为您的列表项添加一个键,以便 vue 可以跟踪每个项目并显示相关数据 (https://vuejs.org/v2/guide/list.html#key)。

    Vue 2:

    <li 
      v-for="(user, key) in users | filterBy filterCool" 
      :key="key"
    >
     {{ user.name }}
    </li>
    

    Vue 1:

    <li 
      v-for="user in users | filterBy filterCool" 
      track-by="$index"
    >
     {{ user.name }}
    </li>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多