How to add a bunch of global filters in Vue.js?

Create a filters.js file.

import Vue from "vue"

Vue.filter("first4Chars", str => str.substring(0, 4))
Vue.filter("last4Chars", str => str.substring(str.length - 4))

Import it into your main.js.

import Vue from 'vue'
import App from './App'
import "./filters"

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
})

Here is a working example.

Side note: If you get a "Vue not found" type of error, as a test try importing filters after the new Vue() declaration, like this:

import Vue from 'vue'
import App from './App'

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
})

import "./filters"

I think the best way is to use the pluginfeature from VueJS

  1. Create a filters folder and put all of you filters there ...

    - filters
      | - filter1.js
      | - index.js
    
  2. In the filter file export the function you need, in this example I'll use a uppercase filter:

    export default function uppercase (input) {
        return input.toUpperCase();
    }
    
  3. In the index.js import and create a plugin:

    import uppercase from './filter1';
    
    
    export default {
         install(Vue) {
             Vue.filter('uppercase', uppercase);
         }
    }
    
  4. In you main.js file use it

    import filters from './filters';
    import Vue from 'vue';
    
    Vue.use(filters);
    

Tags:

Vue.Js

Vuejs2