How to filter items in Vue 3?

radiorz picture radiorz · Feb 18, 2021 · Viewed 10.3k times · Source

In Vue 2, we filter items conveniently just using | and filters. But it isn't in Vue 3.

As we know,we can just use "computed" to change a value to another.

But how can I change values of an array?

Vue 2

<template>
<ul>
  <li v-for="(index,value) in array1" :key="index">
   {{ value | valuefilter}}
  </li>
</ul>
</template>
<script>
...
export {
...
  filters:{
    valuefilter(value){
      return '$'+ value
    }
  }
...
}
</script>

Answer

Dan picture Dan · Feb 18, 2021

Use a computed to filter the data beforehand to the way you want it, then iterate over that computed instead of the raw data.

This is essentially what a filter would do, but with the advantage of keeping the template a little clearer from the logic in the component:

Template

<ul>
  <li v-for="(value, index) in filtered" :key="index">
   {{ value }}
  </li>
</ul>

Options API

data: () => ({
  array1: [1,2,3,4,5]
}),
computed: {
  filtered() {
    return this.array1.map(item => `$${item}`);
  }
}

Composition API

setup() {
  const array1 = ref([1,2,3,4,5]);
  const filtered = computed(() => array1.value.map(item => `$${item}`));
  return {
    filtered
  }
}