Error creating global filters with vues

0

I'm trying to create some filters globally in vues but I'm getting the error "Failed to resolve filter".

My main.js is like this

import Vue from 'vue';
import VueResource from 'vue-resource';

Vue.use(VueResource);

Vue.filter("teste", function(value){
        return "OK";
})
    
asked by anonymous 07.03.2018 / 21:26

1 answer

0

You probably were not able to import the desired filter. What I recommend doing in case of a global filter:

  • Create a separate js file, in a filters folder for example. Each file will be a filter, example below a simple filter:
  • name-substr-format.js

    export function nameSubstrFormat (name, number = 33) {
      if (name) {
        return name.substring(0, number)
      }
    
      return ''
    }
    

    The above filter is a file that exports only one function, in which case its functionality is to limit the number of characters in a string. If nothing happens, it returns a maximum of 33 characters.

  • Now import it into your main.js and call it in your Vue instance:
  • import { nameSubstrFormat } from './filters/name-substr-format' Vue.filter('nameSubstrFormat', nameSubstrFormat)

  • To use it directly in your HTML, just call it inside a tween, after the pipe ("|"), where the first parameter becomes the tween variable. / li>

    <span>{{ nome | nameSubstrFormat(20) }}</span>

    Note that it can be used both with variables within its data() , and computed variables ).

        
  • 07.03.2018 / 23:17