In my application, I have a lot of utility functions that do little things from parsing strings to making toasts and so on.
My question is how do I access these in other .vue files? I don't want to rewrite these functions for every new Vue component that I write.
Will I be able to use these by importing one component into another? (Vue complains if I don't add the component in the template of another, meaning I can't just import that JavaScript).
If so, is that a good thing to do? What's the standard way to do this?
Sharing functions among Vue.js components
-
- Posts:107
Sharing functions among Vue.js components
MarPlo
Posts:186
You can use Mixins.
1. Import the component which you need.
2. add mixin array as below in your component just above the data section (or wherever possible):
Call the method you want using:
More you can find it here: Vue Mixins
Or:
Move them all to a common utilities module, 'src/utils.js', then each Vue component can import as needed:
Then, in .vue files:
1. Import the component which you need.
2. add mixin array as below in your component just above the data section (or wherever possible):
Code: Select all
mixins:[yourimportedcomponent], data:...
Code: Select all
this.theMethodYouWant();
Or:
Move them all to a common utilities module, 'src/utils.js', then each Vue component can import as needed:
Code: Select all
// src/utils.js
const funcA = () => {
console.log('funcA');
}
const funcB = () => {
console.log('funcB');
}
export { funcA, funcB }
Code: Select all
// VueComponentA.vue
import { funcA } from 'path/to/utils';
// VueComponentB.vue
import { funcB } from 'path/to/utils';