0

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/sensible thing to do? What's the standard way to do this?

2 Answers 2

2

Mixins is a concept you can try.

  1. import the component which you need.

  2. add mixin array as below in your component just above the data section (or wherever possible)

    mixins:[yourimportedcomponent], data:....

  3. Call the method you want using this.theMethodYouWant();

More you can find it here https://v2.vuejs.org/v2/guide/mixins.html

Sign up to request clarification or add additional context in comments.

Comments

2

You could create plugin that exposes the functions on Vue. Plugins documentation

// group utils functions together 
Vue.prototype.$utils = {
    funcA: function () {  ...  },
    funcB: function () {  ...  }
} 

or

Move them all to common utilities module, src/utils.js, then each Vue component can import as needed:

// src/utils.js
const funcA = () => {
    console.log('funcA');
}

const funcB = () => {
    console.log('funcB');
}

export { funcA, funcB }

// VueComponentA.vue
import { funcA } from 'path/to/utils';

// VueComponentB.vue
import { funcB } from 'path/to/utils';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.