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.
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;
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");
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>
You can check helper function by starting npm server.
Output