Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

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

I want to make use of a few global filters in a Vue.js app. I know I need to define them before my main Vue instance, but sticking them all in the 'main.js' file doesn't seem right to me from a code organisation point of view. How could I have the definitions in a separate file, imported to 'main.js'? Can't quite get my head around the import/export stuff for this.

question from:https://stackoverflow.com/questions/47004702/how-to-add-a-bunch-of-global-filters-in-vue-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...