1

I have a class and method that I need to import globally, so that I could avoid importing it again in each Vue file. I usually import my own class and method in each Vue file like this:

// in myFunc.js
export const fn = {
  myFunc: function(param) { alert(param) }
}

// then I use it like this
import {fn} from '@/assets/js/myFunc.js';
fn.myFunc('Lorem ipsum');

In main.js, I tried the following code, which does not work:

import {fn} from '@/assets/js/myFunc.js';

Vue.mixin({
  components: { fn },
})

How do I import the class/methods globally?

tony19
  • 125,647
  • 18
  • 229
  • 307
Ashtav
  • 2,586
  • 7
  • 28
  • 44

1 Answers1

1
import Vue from 'vue'
import { fn } from '@/assets/js/myFunc.js';

Vue.prototype.$fn = fn

And then in your component.

this.$fn.myFunc()

Adding Instance Properties.

There may be data/utilities you’d like to use in many components, but you don’t want to pollute the global scope. In these cases, you can make them available to each Vue instance by defining them on the prototype.

tony19
  • 125,647
  • 18
  • 229
  • 307
Andrew Vasylchuk
  • 4,671
  • 2
  • 12
  • 30
  • `this.$fn.myFunc(); ` it's work, by the way, can we call the method without write `this.$fn.myFunc()` just `myFunc()` ??, – Ashtav Aug 22 '19 at 07:17
  • Yes, to achieve that you should polute global object (`window` in browser - `window.myFunc = function() { console.log('I am in the global scope!') }`). But it's considered a bad practise. – Andrew Vasylchuk Aug 22 '19 at 07:58