Skip to content
Advertisement

How do I create a function library which I can used across all my Vuejs components?

I currently writing a financial application using Vue.js and Vuetify. I have a few component files and javascript files like

Dashboard.vue
Cashflow.vue
NetWorth.vue
stores.js <- Vue Vuex

I have some functions which I need to use across all the Vue.js and javascript files. Would it be possible for me to perhaps write a function library which can be used across all the component and js files.

function moneyFormat(num)
function IRRCalc(Cashflow)
function TimeValueMoneyCalc(I,N,PV,FV,PMT)
function PerpetualAnnuityCalc(I,PV)
function CarLoanInstallment(V,N)
function HouseLoanInstallment(V,N)

I know in C it is very simple just #include<financial.h> was wondering is there something similar in javascript.

Thanks.

Advertisement

Answer

There are 3 ways to do this:

1/You can create a helper.js file and import it to .vue files

// helper.js

export default {
  function moneyFormat(num) { // some logic}
  
}

// Dashboard.vue

<script>
import helper from "helper.js"  //the path may change depends on where you put the js file
methods: {
  useHelper(value) {
    helper.moneyFormat(value)  
  
  }
}
</script>

2/Another way is bind the function to Vue prototype in main.js

Vue.prototype.$moneyFormat= function moneyFormat(num) {}

then in Dashboard.vue just call this.$moneyFormat(num). No need to import anything

3/ Use mixins. You can search online on how to use this https://v2.vuejs.org/v2/guide/mixins.html

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement