How should Vue filters be bound using TypeScript? It is fairly straightforward with pure js, but I'm running into issue converting it to TypeScript.
The code and compile error are as follows:
app.ts
import * as Vue from 'vue'
...
import * as filters from './util/filters'
// register global utility filters.
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key]);
})
util/filters.ts
export function host (url: string) {
...
}
export function timeAgo (time: any) {
....
}
Compile Error
error TS7017: Element implicitly has an 'any' type because type 'typeof ...' has no index signature.
Going off number 2, because VueJS filters are meant for text transformations, they can only be used in two places: mustache interpolations (the curly braces in your template) and in v-bind expressions.
If you're not using the Vue CLI or do not have a build process, using TypeScript can be a bit too much. But these cases are very few, especially when building apps, like with Ionic Vue. So if you're working with Vue 3, try it out with TypeScript enabled.
js developers generally have the option of developing applications in either plain ol' JavaScript or its more strict type-safe superset, TypeScript. However, Vue 3.0 came with enhanced TypeScript support which provides a simpler, more efficient, and more robust type inference to make it possible to write reliable code.
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)
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
},
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With