How should Vue filters be bound using typescript?
For adding the filter globally, I did something as following
// in customFilter.ts file
import Vue from 'vue';
const testFilter = Vue.filter(
'filterName', () => {
// filter fn
}
);
export default testFilter;
and include this in main.ts
import testFilter from '@/customFilter.ts'
new Vue({
...
filters: {
testFilter
},
...
I register global filters like this:
Inside plugins/filters.ts
:
import { VueConstructor } from 'vue/types/umd'
export default {
install (Vue: VueConstructor) {
Vue.filter('someFormatFunc1', function someFormatFunc1(value) {
// Your formatting function
})
Vue.filter('someFormatFunc2', function someFormatFunc2(value) {
// Your formatting function
})
}
}
Then inside main.ts
:
import filters from './plugins/filters'
Vue.use(filters)
I'm using a library called vue-property-decorator where you can do something like:
import { Component, Vue } from 'vue-property-decorator'
@Component({
name: 'ComponentName',
filters: {
filterName(value: any) {
return 'Hello filter'
}
}
})
export default class ComponentName extends Vue {
textToFormat = 'Hello world'
}
Then to apply the filter:
<p>{{ textToFormat | filterName }}</p>
Happy coding!