How to filter items in Vue 3?

Viewed 18326

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>
3 Answers

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

If you want to set it as a global filter and make it available to all your app components, do the following:

main.js

const app = createApp(App)

app.config.globalProperties.$filters = {
  valueFilter(value) {
    return '$' + value
  }
}

MyComponent.vue

<template>
<ul>
  <li v-for="(index,value) in array1" :key="index">
   {{ $filters.valueFilter(value) }}
  </li>
</ul>
</template>
Related