Custom Filters in Vue.js

Since I’ve started contracting, I seem to always work on my own. It’s can be difficult sometimes, especially when you have to pick up a new framework. You start to have lots of questions about approach or simply just need some validation. I find myself having a good old nose around in source code to see how other devs implement things from time to time. It’s great!

I came across this one a while back but forgot to share it. Here’s how to add lots of custom filters to your Vue.js project quickly and efficiently. I saw this on vue-hackernews-2.0 and love the simplicity. Hope it helps!

// utils/filters.js
export function timeAgo (time) {
  const between = Date.now() / 1000 - Number(time)
  if (between < 3600) {
    return pluralize(~~(between / 60), ' minute')
  } else if (between < 86400) {
    return pluralize(~~(between / 3600), ' hour')
  } else {
    return pluralize(~~(between / 86400), ' day')
  }
}

function pluralize (time, label) {
  if (time === 1) {
    return time + label
  }
  return time + label + 's'
}

Register global utility filters.

// app.js
import Vue from 'vue'
import * as filters from './util/filters'

// register global utility filters.
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Use them in your templates

<template>
    <div class="by">
        <router-link :to="'/user/' + comment.by"></router-link>
        { { comment.time | timeAgo } } ago
    </div>
</template>

Note: the mustaches are a bit strange, can’t seem to render them properly in Jekyll