Creating a simple Vue pluralize filter
Karolis

Karolis @krusenas

About: Principal Engineer @ Lightning.AI, maker of Webhook Relay, Synpse, Meteron Projects: - webhookrelay.com - keel.sh

Location:
London
Joined:
Nov 1, 2018

Creating a simple Vue pluralize filter

Publish Date: Sep 7 '19
65 5

There are many options how to create a pluralize function but in Vue you should probably use filters. Let's create one as it's always handy to have one.

Step 1: Add pluralize package

Let's use https://github.com/blakeembrey/pluralize to do the heavy lifting:

yarn add pluralize
Enter fullscreen mode Exit fullscreen mode

Step 2: Register filter

Our pluralize filter will take two arguments - first one is the left variable in the filter and second is the filter function argument (depends on your code structure, but it's usually main.js or a dedicated filters file):

// .. your other imports
import pluralize from 'pluralize'

// .. your other code

Vue.filter('pluralize', function (value, number) {
  return pluralize(value, number)
})
Enter fullscreen mode Exit fullscreen mode

Step 3: Use the filter!

Now, to use the filter on the left we give it the word we want to pluralize and as an argument we pass the count:

{{ tunnels }} {{ 'tunnel' | pluralize(tunnels) }}
Enter fullscreen mode Exit fullscreen mode

That's it :) Now, based on tunnels variable it will be either '1 tunnel' or '50 tunnels'.

I hope this will be useful to you once you need it!

Comments 5 total

  • Chris Achard
    Chris AchardSep 8, 2019

    I can't believe I didn't think to look for a pluralizer before as an npm module... of course it exists! Thanks :)

  • Yuyu
    YuyuSep 8, 2019

    Nice tips on making your own filte.

    • Karolis
      KarolisSep 8, 2019

      I am usually using quite a lot of filters in my applications for various things like encoding/decoding base64, pretty printing JSON and so on. Filters are really great! :)

  • aadill77
    aadill77Sep 9, 2019

    we can use Point Free Expression in vue.filter as the functions share the same shape.

    Vue.filter('pluralize', pluralize);

  • Gonçalo Morais
    Gonçalo MoraisMay 21, 2020

    Nice tip! Looking at the documentation, if you add true to your return pluralize(value, number) (making it return pluralize(value, number, true)), you could remove the first {{}} and have it simply {{ 'tunnel' | pluralize(tunnels) }}.

Add comment