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