Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vue.js how do I write custom filters in separate file and use them in various components by declaring in main.js?

Tags:

I tried doing this, but it does not work.

// filter.js

export default {
    converTimestamp: function (seconds) {
      var date = new Date(seconds * 1000);
      return date.toDateString();
    }
};

// main.js

import customFilters from './store/filters';
like image 386
Dinǝsh Gupta Avatar asked Jul 12 '17 09:07

Dinǝsh Gupta


People also ask

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.

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 a custom JavaScript file into Vue?

There are two ways to import a JavaScript library to the Vue Component. The first is to import a local JavaScript library. Here, you can import the JavaScript library by using the 'import' keyword inside the script tag of your Vue file. import * as mykey from '../assets/js/mykey.


1 Answers

Here's an example:

// MyFilter.js
import Vue from 'vue';

Vue.filter('myFilter', value => {
  return value.toUpperCase();
});
// main.js
import './MyFilter.js';

If you don't want to register the filters globally, you can do it like this:

// MyFilter.js
export default function (value) {
  return value.toUpperCase();
}
// MyComponent.vue
import MyFilter from './MyFilter.js';

export default {
  filters: {
    MyFilter,
  },
};
like image 166
Decade Moon Avatar answered Sep 18 '22 01:09

Decade Moon