Home>

I made a simple filter with Vue-CLI.

in main.js

Vue.filter('TimeAndMinutes_24h', function (value) {
  var tmpDt = new Date(value);
  return tmpDt.getHours() + ":" + tmpDt.getMinutes();
});

In the template
{{val.start | TimeAndMinutes_24h}}
Then, if the input is "2020-07-30 14:13:30", the display will be "14:13", which satisfies the requirement.

However, I want to use some filters other than this display format, but I don't think it is realistic to add more to main.js.
I would like to define the common three-digit grouping etc. in a separate file and use it as a normal one.

So should I define it in a separate file and import it like mixins? I thought, but I do not know the actual method.

Prepare fiter.js as a separate file

export default {
    filters: {
        TimeAndMinutes_24h(value) {
            var tmpDt = new Date(value);
            return tmpDt.getHours() + ":" + tmpDt.getMinutes();
        }
    }
}

in main.js

import Ft from'./filters/filter.js'
Vue.filter(Ft);


I tried it with Vue.use and it does not cause an error itself, but I am just told that the filter cannot be found in the console...

Is there any way?

  • Answer # 1

    How to register a global filter

    To register a filter globallyfilterIDWhenfilter functionTo pass.
    In the example belowucOrlcButfilterID, An anonymous functionfilter functionis.

    const toUpperCase = function(value) {
      return value.toUpperCase();
    }
    const toLowerCase = function(value) {
      return value.toLowerCase();
    }
    Vue.filter('uc', toUpperCase);
    Vue.filter('lc', toLowerCase);
    How to write the filter function in a separate file Example 1

    This is an example of defining the filter function in a separate file and registering the filter in main.js.

    ./filter/index.js

    export function toUpperCase(value) {
      return value.toUpperCase();
    }
    export function toLowerCase(value) {
      return value.toLowerCase();
    }

    main.js

    import * as filters from "./filter";
    Vue.filter('uc', filters.toUpperCase);
    Vue.filter('lc', filters.toLowerCase);
    Example 2

    This is an example in which the definition of the filter function and the registration of the filter are in separate files and that is done in main.js.

    ./filter/index.js

    import Vue from "vue";
    Vue.filter('uc', function(value) {
      return value.toUpperCase();
    });
    Vue.filter('lc', function(value) {
      return value.toLowerCase();
    });

    main.js

    import "./filter";
    Referenced page

    Custom filter

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