Introduction to Vue.js Filters

Introduction to Vue.js Filters

Published 26. jun 2018 05:38 by Stein Ove Helset

Vue's filters are a smart way of applying formatting to a dynamic value in a template. The filters does not actually change to underlying data, it's just for rendering.

A simple filter

Let's say that you have a component where you want to show a message, but if it's more than 20 characters long, you truncate it and add three dots at the end. Here is an example of how you can achieve that using a filter:


<div id="app">
  <p>{{ message|truncate }}</p>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js! This is a message that is longer than 20 characters long.'
  },   filters: {     truncate: function(value) {       if (value.length > 20) {         value = value.substring(0, 17) + '...';       }
      return value
    }   } }) </script>

We can make some edits to this filter and make it possible to pass one more value to the filter. This value can be the maximum number of characters allowed.


<div id="app">
  <p>{{ message|truncate(20) }}</p>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js! This is a message that is longer than 20 characters long.'
  },   filters: {     truncate: function(value, limit) {       if (value.length > limit) {         value = value.substring(0, (limit - 3)) + '...';       }
      return value
    }   } }) </script>

Chaining filters

A cool thing about filters is that they can be chained. So instead of adding the three dots in the truncate filter, we'll create another filter for adding tailing content.


<div id="app">
  <p>{{ message|truncate(20)|tailing('...') }}</p>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js! This is a message that is longer than 20 characters long.'
  },   filters: {     truncate: function(value, limit) {       return value.substring(0, limit)     },     tailing: function(value, tail) {       return value + tail;     }   } }) </script>

I know that seemed like a weird example and it's not something you would do in the real world, but it shows how you can chain filters in a simplified way.

There are tons of things you can do with filters and I encourage you to try to build some for your self. It's also possible to download packages containing smart filters like truncate, capitalizing, transforming and similar. vue-filter is a package containing a lot of different things you often need. You don't always need to reinvent the wheel, but it's nice to know how something works.

Read more about Vue on A Hacker's Day:
Introduction to Vue.js Props
Introduction to Vue.js Slots
Communicating between Vue.js components

Share this post

Comments

No comments yet

Add comment