Onyx
Onyx

Reputation: 5772

Where should I put general utility functions which will be used by multiple Vue.js components?

Usually I create the function in the component which is gonna use the function, however, I'm starting to have the need to use a certain function in 2 or more components, which means that right now I would have to copy and place it in the other components. This is obviously less than optimal, so I am wondering where should I place those functions. To show you what I mean by general utility functions I'll add one here:

winrate(wins, losses) {
    let games = wins + losses
    return Math.round(wins * 100 / games) + '%'
}

Nothing special, it just takes wins and losses and then returns win rate.

I am using Vuex and realistically I could put them in the Vuex store, however, I'm not sure if that's the best option so this is why I'm asking you guys.

Upvotes: 5

Views: 1655

Answers (1)

Andrew Vasylchuk
Andrew Vasylchuk

Reputation: 4779

It's common practice to store such functions (called helpers) in files such as helpers.js or utils.js, which code could look something like this:

export function winrate(wins, losses) {
    let games = wins + losses
    return Math.round(wins * 100 / games) + '%'
}

And then just import that helper in your component:

import { winrate } from './path/to/helpers.js'

export default {
  // ...
  methods: {
    method() {
      console.log(winrate(1, 2))
    }
  }
  // ...
}

Upvotes: 8

Related Questions