Reader small image

You're reading from  Vue.js 2 Cookbook

Product typeBook
Published inApr 2017
Reading LevelBeginner
PublisherPackt
ISBN-139781786468093
Edition1st Edition
Languages
Right arrow
Author (1)
Andrea Passaglia
Andrea Passaglia
author image
Andrea Passaglia

Andrea Passaglia was born in Genoa, in northern Italy. Interested about technology since his parents gave him a toy computer when he was a boy, he started studying web technologies at an early age. After obtaining his master's degree in computer engineering he worked on the design and implementation of web interfaces for companies of various sizes and in different industries (healthcare, fashion, tourism, and transport). In 2016 he moves in the silicon valley of Europe to tackle new problems in the banking industry at the Edgeverve Dublin Research and Development Labs. A backend technologist by trade, Vue.js is his first tool to bring to life his creations when it comes to the frontend. Andrea is married to a lovely Russian girl from Siberia and they often cook together mixing culinary traditions.
Read more about Andrea Passaglia

Right arrow

Formatting your text with filters


The first version of Vue came bundled with some text filters that helped format text and solve some common problems.

In this new version, there are no built-in filters (except the equivalent of the JSON filter covered in the next recipe). I think this is because it's very easy to write your own filter and also very easy to find online libraries that do a much better job in specialized situations. Finally, filters have somewhat changed purpose: they are more for post-processing now and less for actual filtering and sorting arrays.

To demonstrate how easy it is to create a filter, we will recreate a filter of the old version of Vue: capitalize.

Getting Ready

You don't need any particular knowledge to complete this recipe.

How to do it...

Sometimes we have some strings floating around in our variables like labels. When we put them in the middle of a sentence they work fine, but on the other hand they don't look very good at the beginning of a sentence or bullet point.

We want to write a filter that will capitalize whatever string we put into it. If, for example, we want the string hello world to start with a capital H, we'd like to be able to write:

{{'hello world' | capitalize }}

If we try to run this as HTML in a Vue app, it will complain [Vue warn]: Failed to resolve filter: capitalize.

Let's create the filter and add it to Vue's internal list of filters:

  1. Write the following JavaScript to register a filter and instantiate Vue:
        Vue.filter('capitalize', function (string) { 
          var capitalFirst = string.charAt(0).toUpperCase() 
          var noCaseTail = string.slice(1, string.length) 
            return capitalFirst + noCaseTail 
        }) 
        new Vue({el:'#app'})
  1. In the HTML section, write:
        {{'hello world' | capitalize }}
  1. Run your code and notice how the text now reads Hello world.

How it works...

The pipe sign indicates that the following is the name of a filter; in our case capitalize is not in Vue's list of filters, hence the warning. Vue will print the string as is.

What Vue will do before even starting is register our filter (with Vue.filter) in its asset library. Vue has an the internal filters object and will create a new entry: capitalize. Every time it sees the pipe symbol it will look for a corresponding filter. Remember to write it before the actual instantiation of a Vue instance because otherwise Vue will not find it.

The working of the filter is very basic JavaScript, in fact, a better way to write this filter with ES6 would be:

Vue.filter('capitalize', function (string) { 
  var [first, ...tail] = string 
  return first.toUpperCase() + tail.join('') 
})

If you are not familiar with ES6, here is a brief explanation. The second line is called a destructuring assignment of string; in particular we are interpreting string as an array of characters, separating the first character into first and putting all the other characters in tail. This is a faster way to assign different parts of an array to multiple variables. The other thing that may seems mysterious is that join(''). Since tail is now an array of characters, we need some means to re-join the single letters into a compact string. The argument of join represents a separator between the single characters. We don't want any, so we pass an empty string.

In the next chapter, you will find more recipe for filters and cover other real use cases.

Previous PageNext Page
You have been reading a chapter from
Vue.js 2 Cookbook
Published in: Apr 2017Publisher: PacktISBN-13: 9781786468093
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Andrea Passaglia

Andrea Passaglia was born in Genoa, in northern Italy. Interested about technology since his parents gave him a toy computer when he was a boy, he started studying web technologies at an early age. After obtaining his master's degree in computer engineering he worked on the design and implementation of web interfaces for companies of various sizes and in different industries (healthcare, fashion, tourism, and transport). In 2016 he moves in the silicon valley of Europe to tackle new problems in the banking industry at the Edgeverve Dublin Research and Development Labs. A backend technologist by trade, Vue.js is his first tool to bring to life his creations when it comes to the frontend. Andrea is married to a lovely Russian girl from Siberia and they often cook together mixing culinary traditions.
Read more about Andrea Passaglia