Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vue.js

vuejs2

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.

like image 484
John Moore Avatar asked Oct 29 '17 20:10

John Moore


People also ask

Where can Vue filters be applied?

Vue Filters differ from computed properties in two ways. Going off number 2, because VueJS filters are meant for text transformations, they can only be used in two places: mustache interpolations (the curly braces in your template) and in v-bind expressions.

How do I import custom components to Vue?

STEP 01: First, Import the Child Component into the Parent Component inside script tag but above export default function declaration. STEP 02: Then, Register the Child Component inside the Parent Component by adding it to components object. STEP 03: Finally, Use the Child Component in the Parent Component Template.

What is VUE mixin?

Mixins in Vue JS are basically a chunk of defined logic, stored in a particular prescribed way by Vue, which can be re-used over and over to add functionality to your Vue instances and components. So Vue mixins can be shared between multiple Vue components without the need to repeat code blocks.


2 Answers

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" 
like image 82
Bert Avatar answered Sep 20 '22 15:09

Bert


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); 
like image 40
Lucas Katayama Avatar answered Sep 22 '22 15:09

Lucas Katayama