How to Create Helper Function in Vue Js 3

AuthorHariom Prajapati

Pubish Date29 Dec 2022

categoryVue JS

In this tutorial, we will learn how to create a helper function in vue js 3 and use it anywhere in the project without importing any files. By using a helper function, we can write our code in very few lines, this will improve the performance of our application and we do not need to create any function again and again.

 

Here we created a helper function by taking the example of a number format. You can create a new helper function according to your need like below example.

 

Step 1 - Create a helper folder in src directory 

 

Step 2 - Create an index.js file in src/helper

 

src\helper\index.js

const myPlugin = {
    install(app) {
        app.config.globalProperties.$numFormat = (key) => {
            return Number(key).toLocaleString();
        },
        app.config.globalProperties.$numFormatWithDollar = (key) => {
            return key ? '$' + Number(key).toLocaleString() : '-';
        }
    }
}
 
export default myPlugin;

 

Step 3 - Import the helper in main.js file

Here you need to add your helper file.

 

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import helper from './helper'
const app = createApp(App);
 
app.use(router);
app.use(helper);
 
app.mount("#app");

 

Step 4 - Create a view component 

Now you need to create a component for a view.

 

<template lang="">
    <div>
        <h1>Number format :  {{ $numFormat(100000) }}</h1>
        <h1>Number format with dollar sign :  {{ $numFormatWithDollar(100000) }}</h1>
    </div>
</template>

 

Step 5 - Now start the npm server

You can check helper function by starting npm server.

 

Output

How to Create Helper Function in Vue Js 3

Comments 0

Leave a comment