Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should Vue filters be bound using typescript?

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.

like image 407
pulekies Avatar asked Jun 02 '17 16:06

pulekies


People also ask

Where do you put Vue filters?

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.

Should I use TypeScript for Vue?

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.

What is VUE TypeScript?

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.


2 Answers

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)
like image 112
rockstarr-programmerr Avatar answered Sep 24 '22 02:09

rockstarr-programmerr


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
  },
...
like image 27
Sanju Avatar answered Sep 24 '22 02:09

Sanju