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"

Leave a Comment