【问题标题】:VueJS computed filter function not workingVueJS计算过滤器功能不起作用
【发布时间】:2020-10-21 00:20:39
【问题描述】:

所以我正在尝试实现这里解释的功能Vuejs Search filter 但是计算中的函数似乎不起作用,甚至没有记录任何内容,这是我的代码:

...
<a-layout-header style="background: #fff; padding: 0">
    <a-input-search 
      placeholder="Search everything" 
      style="width: 200px; marginLeft: 20px" 
      v-model="searchData"
    />
    <a-button type="primary" style="marginLeft: 20px">
      + New
    </a-button>
</a-layout-header>
...
data() {
  return {
    data: json,
    collapsed: false,
    item_key: 1,
    searchData: ''
  };
},
computed: {
  searchResult() {
    if (this.searchData) {
      return this.data.filter((item) => {
        return this.searchData.toLowerCase().split(' ').every(v => 
                  item.title.toLowerCase().includes(v));
        })
    } else {
      return this.data;
    }
  }
},

编辑:过滤它的数据作为道具传递给子组件,我有一个 ant-design 表来获取它:

<a-table
  v-if="this.item.toString() === '1'"
  :columns="columns"
  :row-key="record => record.guid"
  :data-source="normalData"
  :pagination="pagination"
  :row-selection="rowSelection"
>
</a-table>

【问题讨论】:

  • 首先,为简洁起见,您是否在“json”语句中省略了“数据”?你真的在某个地方调用你的计算吗?
  • 不,我的数据实际上是从文件 data.json 导入的 json
  • 我对 Vue 还是很陌生,我需要在 vue 文件中的某处调用 computed 吗?
  • 我只是想知道您是如何调试计算值的。从我的角度来看,它看起来不错。只需在模板中的某处添加{{ searchResult }} 即可查看计算的值是多少!或者你可以使用 chrome "vuejs devtools" 扩展来调试你的 Vuejs 应用
  • 另外,您可以尝试使用虚拟“数据”对象(不是来自 json 文件,只需在组件中自己创建对象)来检查您是否真的有数据。

标签: vue.js


【解决方案1】:

这就是你应该如何实现搜索过滤器:

...
<div>
    <input
      placeholder="Search everything" 
      v-model="searchData"
    >
    <div v-for="(item,index) in filteredList" :key="index">
      {{ item.title }}
    </div>
</div>
...
data() {
  return {
    data: [
  {
    id: 1,
    title: 'First item',
  },
  {
    id: 2,
    title: 'Second item',
  },
  {
    id: 3,
    title: 'Third item',
  },
],
    searchData: ''
  };
},
computed: {
  filteredList() {
    const filter = this.searchData.trim().toUpperCase();
    return filter ? this.data.filter(item =>
    {
      return item.title.toUpperCase().indexOf(filter) !== -1;
    }) : this.data;
  }
},

【讨论】:

  • 所以这是我的错,我没有指定整个功能,我过滤它的数据实际上是作为道具传递给子组件的,我有一个 ant-design 表可以得到这个数据
  • 您可以更改模板以使用 AntDesign 表 - 它不会以任何方式影响 JavaScript 代码。只需将filteredList 发送到餐桌即可。
猜你喜欢
  • 2020-09-06
  • 2018-01-04
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
相关资源
最近更新 更多