How to filter items in Vue 3?

12,848

Solution 1

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
  }
}

Solution 2

Filters are removed from Vue 3.0 and no longer supported

Here is the way you can use the filter in Vue 3

click the link below:

https://v3-migration.vuejs.org/breaking-changes/filters.html

Share:
12,848

Related videos on Youtube

radiorz
Author by

radiorz

Updated on June 04, 2022

Comments

  • radiorz
    radiorz almost 2 years

    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>
    
  • radiorz
    radiorz about 3 years
    so why still use computed?can i just do it this way: ``` const filtered =array1.value.map(item => '$'+ item) ```
  • Dan
    Dan about 3 years
    You could do that, it just wouldn't be reactive. If array1 changed later, filtered would not, but a computed would recalculate.