Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globally-available mixin in VueJS

I'm trying to create a mixin that's globally available, but not automatically injected into every component. i.e. i do NOT want this: Vue.mixin({...});

I set up the project according to these instructions. This is my project structure. I also have assets/js/mixins.js file in there containing my mixins.

I would like to be able to do this in my individual .vue files (many of my components use myMixin but not all of them):

<script>
export default {
    mixins:[myMixin],
    data:{....}
}
</script>
<template>
  <!-- some template code -->
</template>

So far the only way to do that is to add this line to the top of every component that needs it:

import {myMixin} from './assets/js/mixins.js"

but is there a way to do this once and have myMixin variable available globally? I've tried including it in main.js and in app.vue but I still get "myMixin is not defined" error if I try to use myMixin in any of the child components.

Or is there another way to register a mixin that doesn't require me typing the path to the mixins.js file in each component?

like image 367
ierdna Avatar asked Apr 08 '16 02:04

ierdna


1 Answers

I would suggest setting your mixin up as a plugin. To do that, wrap it within an function call install and export the install function. Then, wherever your instantiate your app, you can simply do Vue.use(yourMixin):

Docs:

https://vuejs.org/guide/plugins.html

http://vuejs.org/api/#Vue-mixin

Example:

//- build your mixin
const mixin = {
  // do something
}

//- export it as a plugin
export default {
  install (Vue, options) {
    Vue.mixin(mixin)
  }
}

//- make it globally available
import myMixin from './myMixin'
Vue.use(myMixin)

Vue.use calls in the install fn(), so all subsequent Vues (or all if none have yet been created) have the mixin functionality

Careful of namespace clashes on globally available mixins (!)

like image 50
Tremendus Apps Avatar answered Sep 28 '22 08:09

Tremendus Apps