【问题标题】:filter elements of an array and display them using the same array过滤数组的元素并使用相同的数组显示它们
【发布时间】:2022-11-11 01:12:27
【问题描述】:

我在 pinia 中有一个状态,它是一个对象数组,我通过执行获取添加元素,在一个组件中我得到这个数组并使用 v-for 运行它并显示一些卡片,在我运行的父组件中数组我有一些按钮可以按类型过滤数组的元素,为此在状态下我创建另一个数组,过滤后的元素将在其中去,并且在组件中我验证它是否为空,添加原始元素大批。我创建了一个函数,我命令在每个按钮上调用它,向它传递我要过滤的类型,在这里我只是使用过滤器遍历过滤元素的数组,并检查类型是否相同正如我传递给函数的内容一样,将其添加到过滤器数组中。为此,我传入 v-for 新的过滤器数组以显示每个按钮的过滤器数组,但是由于我可以在不使用另一个数组的情况下执行此操作,因此我想使用原始数组,因为我从输入中进行搜索并且我这样做了它到原始数组,这可能吗?我认为使用计算机可以完成,但我找不到方法。

状态:

export const useObjStore = defineStore('ObjStore', {
  state: () => {
    return {
      array: [],
      filtersArray: []
    }
  },
  getters: {},
  actions: {
    fetchElements() {
      // .....
    }
  }
})

零件:

<button
  class="d-flex align-items-center button-option cursor-pointer px-2"
  @click="filterByType('uno')"
>Uno</button>

<button
  class="d-flex align-items-center button-option cursor-pointer px-2"
  @click="filterByType('two')"
>Two</button>

<button
  class="d-flex align-items-center button-option cursor-pointer px-2"
  @click="filterByType('three')"
>Three</button>

我循环遍历数组的组件:

<card
  v-for="(elem, n) in filtersArray"
  :key="`elem-${n}`"
  :elem="elem"
  class="mb-4"
/>
if (filtersArray.value.length === 0) {
  filtersArray.value = array
}

const filterByType = (type) => {
  filtersArray = array.filter((val) => val.type === type)
}

【问题讨论】:

    标签: arrays vue.js


    【解决方案1】:

    您可以在 pinia 商店中管理filterBy 状态,该状态将跟踪已应用的过滤器类型。然后,您可以使用像这样的 getter 计算值:

    getters: {
        filteredArray: (state) => state.filterBy ? state.array.filter((val) => val.type === state.filterBy) : state.array;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      相关资源
      最近更新 更多