Writing a filter in Vue.js

08.09.19

Consider Vue 2. Filters in Vue are used to format text. Unlike Angular, where similar functionality is called pipes, Vue has no built-in filters. You need to write them yourself. Consider an example filter for removing tags from a string, stripTags.

Let's write the following in a separate file:

// stripTags.js
 
export default (value) => {
    let div = document.createElement("div");
    div.innerHTML = value;
    let text = div.textContent || div.innerText || "";
    return text;
}

Connect the filter globally

import Vue from 'vue';
import stripTags from './filters/stripTags';
 
Vue.filter('stripTags', stripTags);

Use:

{{ message | stripTags }}

Filters can be combined in chains:

{{ message | filterA | filterB }}

Since a filter is a function, it can take arguments

{{ message | filter(arg) }}

In this case, message will be the first argument, arg the second.

blog comments powered by Disqus