I have small functions which needs to be used in many ponents. 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?
I have small functions which needs to be used in many ponents. 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?
Share Improve this question asked Nov 29, 2018 at 11:52 Shubham ChaudharyShubham Chaudhary 1,4824 gold badges20 silver badges38 bronze badges 1- @AhmedHammad Shouldn't Vuex be used only for state management? The functions I am talking about are just helper functions. – Shubham Chaudhary Commented Nov 29, 2018 at 12:04
2 Answers
Reset to default 4You 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",
ponents: { App },
template: "<App/>",
methods: {
superMessage(value) {
return 'super hello ' + value
}
}
});
Then use these functions inside any ponent:
<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>
You could put these functions in the global JS file, but here are a few alternatives.
- Define the function as a method of the parent Vue ponent, and you can access it via
this.$parent.method();
. You could use a Vuex store, which will definitely be easier if you have a lot of nested child ponents accessing the method.
state: { data: 'hi', }, getters: { data(state){ return Array.from(state.data).reverse().join(''); } }