How to Create Your Own Custom Filters Plugin in Nuxt.JS (V2)

1 Star2 Stars3 Stars4 Stars5 Stars (Be First Rating)

Nuxt.js allows you to define filters that can be used to apply common text formatting. JavaScript plugins to be run before instantiating the root Vue.js Application. This is especially helpful when using your own libraries or external modules to create filters plugin in Nuxt.JS

This tutorial demonstrates step by step basic and simple creating your own custom filters plugin in Nuxt.JS (V2)

Prerequisites

Before starting with this guide, make sure you have been installed Nuxt.JS. If you dont install yet Let’s see How to Install NUXT 2 and Vuetify without Error. On this guides we are using Nuxt.js version 2.3.4


Step 1: Create Custom Filter

For this tutorial, we need to create a plugin for converting simple price with an initial $ sign. the function name istoUSD Now go to the plugins folder and create a file myfilter.js and add or copy/paste the following code into that file

import Vue from 'vue'

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') 
   } 
} 

export function toUSD(value) { 
   return `$${value}`; 
} 

const filters = { timeAgo, toUSD } 

export default filters Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Step 2: Initialize Plugin in Config

Nuxt.JS config is an object containing global configurations. To initialize in global config see below code 

export default {
  plugins: ['~/plugins/myfilter.js']
}

Step 3: Using the Filter in Component and Vuex

To obtain global filter can be accessed with a little bit verbose this.$options.filters.YOUR_FUNCTION()

<template>
<div>
  {{this.$options.filters.toUSD(10)}}
</div>
</template>

Step 4: Test on the Browser

You can now view result in your web browser by visiting your public IP (on the server) or localhost address followed by :port – http://localhost_or_IP:3000 as a default port

 


If this tutorial could help you, please rate above Star button rating and share to help others find it! Feel free to leave a comment below.

Recommended For You

Axfon

About the Author: Axfon

Team committed to share our IT skills and experience through our website which may assist to formulate a task easy