Dinǝsh Gupta
Dinǝsh Gupta

Reputation: 387

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

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';

Upvotes: 21

Views: 13440

Answers (4)

MorganFreeFarm
MorganFreeFarm

Reputation: 3733

For Vue3

Create filters.js file:

const filters = {
    upperCase(value) {
        return value.toUpperCase();
    }
}

export default filters;

import the file in main.js and use it globally with globalProperties:

import { createApp } from 'vue';
import filters from './filters'
const app = createApp({});
app.config.globalProperties.$filters = filters;

Then you can use it directly in template, like that:

{{ $filters.upperCase('some text') }}

Upvotes: 2

Jainil
Jainil

Reputation: 1496

We can create a plugin for that:

// filters.js
import Vue from 'vue'

export function truncate( text, length, suffix = '...' ) {
    if (text.length > length) {
        return text.substring(0, length) + suffix;
    } else {
        return text;
    }
}

export function json( value ) {
    return JSON.stringify(value);
}

const filters = { truncate, json }

Object.keys( filters ).forEach( key => {
    Vue.filter( key, filters[ key ] )
})

then add this new plugin in the config

export default {
  plugins: ['~/plugins/filters.js']
}

Upvotes: 1

clem
clem

Reputation: 424

If you don't have so many filters, you can also define them in a single file:

// filters.js
export default {
    filterA: () => {},
    filterB: () => {},
}

And import them globally:

// main.js
import filters from './filters';
for(let name in filters) {
    Vue.filter(name, filters[name]);
}

Upvotes: 10

Decade Moon
Decade Moon

Reputation: 34306

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,
  },
};

Upvotes: 69

Related Questions