简体   繁体   中英

How can i use filter using Vue 2 which should be compatible for Vue 3

I am using Vue js 2 + version and for my requirement i created a filter for date formatting but i heard that in Vue 3 filter got removed and instead need to use compute or method the problem here how can i write a compatible version for version 2 and version 3

Vue js 2 filter i wrote

<ul>
       
  <li v-for="(info, index) in data">
     {{info.time.data | Filter}}
  <li>
<ul>

Filter request :

    filters: {
  Filter(date){
     return moment.unix(date).utc().format('HH:mm a');
    
    }
  },

How can i write a compatible method which can be used for both version 2 & 3

As stated here https://v3.vuejs.org/guide/migration/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')
}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM