bekwam courses

Vue.js Global Filters

June 8, 2019

Vue.js Filters format content. For instance, one might format a 10-digit US phone number using parentheses, a space, and a dash -- (555) 555-5555 -- even if the data is stored as a pure number (5555555555). This article shows how to define a global Filter that can be used in any component to provide display consistency throughout the app.

This screenshot shows a CodePen containing a top level Vue instance ("app") and a component ("ComponentA"). Both objects display a text field that has been masked by a global Filter called "mask".

CodePen Showing App and Code
Data Masked in App Instance and Component

A Filter is defined using the Vue.filter function. You provide a name and a function that examines the unfiltered input and produces a transformed output. This particular function returns a text string of asterisk characters, one for each character in the input. If the input is empty, then an empty string is returned.


Vue.filter("mask", function (value) {
  if (!value) return "";
  return "*".repeat(value.length);
});

Filters can be restricted to a component as in this article. It's better to make a Filter available app-wide to encourage reuse. These are utility functions that are likely to span views.

If you're using Single File Components as in most projects, a central JavaScript file like main.js is a good place to put your Filter definitions. Any part of the definition or implementation can also be moved out to a dedicated file.

This is the app instance. It applies the filter to a data field "mytext" using the bar notation: {{ mytext | mask }}. I'm also using that notation to pass a masked property to ComponentA.


const app = new Vue({
  el: "#app",
  data: {
    mytext: "secret word"
  },
  template: `
    <div>
    <p>Masked Text: {{ mytext | mask }}</p>
    <component-a :textdata="mytext | mask" />
    </div>
`
});

This is the listing for ComponentA. If you're recreating my CodePen, it must appear before the app instance creation. Although I've passed in an already-masked value, because mask is global, this component could accept an unmasked value and apply the mask Filter via the bar notation within the component.

    
const ComponentA = Vue.component("component-a",{
  props: ["textdata"],
  template: `
    <p>ComponentA Masked Text:
    {{ textdata }}</p>
  `
});
    

Filters are covered in the Vue.js documentation. This article gives an additional example and shows how the Filter can be passed in as a property of a component. Filters help build a consistent display by making formatting available throughout the app. This means that data can be maintained in it's purer form which makes it easier for backend updates another processing.


Headshot of Carl Walker

By Carl Walker

President and Principal Consultant of Bekwam, Inc