In Vue.js, how to write your own filters in a separate file and use them in various components by declaring in main.js?

I tried to do this, but that will 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';
+11
source share
3 answers

Here is an example:

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

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

If you do not want to register filters worldwide, you can do this as follows:

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

export default {
  filters: {
    MyFilter,
  },
};
+29
source

If you do not have 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]);
}
+6
source

We can create a plugin for this:

// 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 to the config

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

Source: https://habr.com/ru/post/1681256/


All Articles