javascriptvue.jsvuejs2vuejs3vue-filter

How to filter items in Vue 3?


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>

Solution

  • 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, plus the advantage of keeping the template a little cleaner:

    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 = reactive([1,2,3,4,5]);
      const filtered = computed(() => array1.map(item => `$${item}`));
      return {
        filtered
      }
    }