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 plugin
feature from VueJS
Create a
filters
folder and put all of you filters there ...- filters | - filter1.js | - index.js
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(); }
In the
index.js
import and create a plugin:import uppercase from './filter1'; export default { install(Vue) { Vue.filter('uppercase', uppercase); } }
In you main.js file use it
import filters from './filters'; import Vue from 'vue'; Vue.use(filters);