Shubham Chaudhary
Shubham Chaudhary

Reputation: 1472

Using global helper function in VueJS

I have small functions which needs to be used in many components. These functions just do some calculations on data and return, and are independent of rest of app. Should I put these functions in JS file at home directory or is there a Vue way to do this thing?

Upvotes: 4

Views: 5485

Answers (2)

Sovalina
Sovalina

Reputation: 5609

You can define your functions inside a global js file (for exemple 'functions.js'), or define them inside the main Vue's methods property:

// functions.js
export function message(value) {
  return 'hello ' + value
}

// and/or

// main.js
new Vue({
  el: "#app",
  components: { App },
  template: "<App/>",
  methods: {
    superMessage(value) {
      return 'super hello ' + value 
    }
  }
});

Then use these functions inside any component:

<template>
  <div>
    <p>{{ message('world') }}</p> <!-- "hello world" -->
    <p>{{ $root.superMessage('world') }}</p> <!-- "super hello world" -->
  </div>
</template>

<script>
import { message } from "./functions"
export default {
  methods: {
    message
  }
};
</script>

Upvotes: 4

Mav
Mav

Reputation: 1190

You could put these functions in the global JS file, but here are a few alternatives.

  1. Define the function as a method of the parent Vue component, and you can access it via this.$parent.method();.
  2. You could use a Vuex store, which will definitely be easier if you have a lot of nested child components accessing the method.

    state: {
        data: 'hi',
    },
    getters: {
        data(state){
            return Array.from(state.data).reverse().join('');
        }
    }
    

Upvotes: 2

Related Questions