[Vuejs]-How can i use filter using Vue 2 which should be compatible for Vue 3

2๐Ÿ‘

โœ…

As stated here https://v3-migration.vuejs.org/breaking-changes/filters.html#overview โ€“ filters using pipe operators will not work in Vue 3, and have to be replaced with methods or computed properties.

It would work both on Vue 2 and Vue 3 if You put timeFilter into methods and change Your template replacing pipe with method call.

But probably computed property would be better optimized since it should cache values (resulting in less operations if input value hasnโ€™t changed).

<ul>
  <li v-for="(info, index) in data" :key="index">
     {{ timeFilter(info.time.data) }}
  <li>
<ul>
methods: {
  timeFilter(date) {
     return moment.unix(date).utc().format('HH:mm a');
  }
}

We can also use global $filters property as suggested in migration strategy (and also @Naren suggested).

In Vue 2 and Vue 3 templates:

<ul>
  <li v-for="(info, index) in data" :key="index">
     {{ $filters.timeFilter(info.time.data) }}
  <li>
<ul>

In Vue 3:

// main.js
const app = createApp(App);

app.config.globalProperties.$filters = {
   timeFilter: date => moment.unix(date).utc().format('HH:mm a')
}

In Vue 2:

Vue.prototype.$filters = {
   timeFilter: date => moment.unix(date).utc().format('HH:mm a')
}
๐Ÿ‘คJan Madeyski

2๐Ÿ‘

Vue 3 does not support filters, As per Vue docs: Filters are removed from Vue 3.0 and no longer supported. But you can still use computed properties for data change listeners otherwise methods suffice. In case if you want to register them globally, use can do like the following

// main.js
const app = createApp(App)

app.config.globalProperties.$filters = {
   timeFilter: (date) => moment.unix(date).utc().format('HH:mm a')
}
<ul>
  <li v-for="(info, index) in data">
     {{ $filters.timeFilter(info.time.data) }}
  <li>
<ul>
๐Ÿ‘คNaren

Leave a comment