Johnny Metz
Johnny Metz

Reputation: 5965

Where to put global helper js functions

I have several helper functions I intend to use throughout my Vue.js 2 application (i.e. within components and vuex). The one I'm using as an example here, toCurrency, converts a number to a currency string. I'm wondering where the best place to put this helper function is. I'm currently putting it at the top of my store.js file (I'm using vuex obviously) and calling it throughout the file. However, this means I also need to define it as a method when I want to use it in components. Is there a better place to put them so I don't have to keep defining it or is this the best place?

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

function toCurrency(num){
    return "$" + num.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}

export default new Vuex.Store({
    state: {
        price: 2
    },
    getters: {
        numString: state => {
            return toCurrency(state.funds)
        }
    },
    mutations: {
        decrementOne: state => {
            state.num --;
            alert("Price decremented to " + toCurrency(state.funds))
        }
    }
})

Upvotes: 1

Views: 1146

Answers (1)

li x
li x

Reputation: 4051

This sounds like a perfect case for Instance Variables. Essentially I would firstly setup an address such as this.$helperfunctions and then proceed to add all of my methods directly onto this instance member after which they will become available to the rest of your application.

import myObjectFullOfMethods from '../somewhere/foo/bar.js';

new Vue({
  beforeCreate: function() {
    this.$helperfunctions = new myObjectFullOfMethods();
  }
})

Upvotes: 2

Related Questions