Useful Vue.js filters

in Code Write a comment

I’ve created a list of useful Vue.js filters for your projects. They are listed in no particular order. This page will be updated, so make sure you add it to your bookmarks and subscribe to my newsletter.

I’ve written a tutorial on how to create custom filters. Please see it first to learn how to create and use custom filters in your Vue.js components.

Truncate a string

Vue filter to truncate a string to the specified length.

Vue.filter('truncate', function (value, length) {
  if (value.length < length) {
    return value
  }

  length = length - 3
  return value.substring(0, length) + '...'
})

Humanable

Vue filter to convert a slug to a more human-friendly form.

Vue.filter('humanable', function (value) {
  var words = value.split(/[-_]+/g)
  var results = []
  for (var i = 0; i < words.length; i++) {
    var letter = words[i].charAt(0).toUpperCase()
    results.push(letter + words[i].slice(1))
  }
  return results.join(' ')
})

Hi, I'm Renat 👋

 


Percentage

Vue filter to convert the given value to percent.

Vue.filter('percentage', function (value, decimals) {
  if (!value) {
    value = 0
  }

  if (!decimals) {
    decimals = 0
  }

  value = value * 100
  value = Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals)
  value = value + '%'
  return value
})

Round

Vue filter to round the decimal to the given place.

Vue.filter('round', function (value, decimals) {
  if (!value) {
    value = 0
  }

  if (!decimals) {
    decimals = 0
  }

  value = Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals)
  return value
})

You can share your most favourite Vue filters in the comments.

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-filters

PS: Make sure you check other Vue.js tutorials, e.g. vue.js scroll to top on route changeusing jQuery with Vue.js (pros and cons).

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment