4
votes

I'm currently learning how to develop an app with Vuejs. I have a main.js file with the code for setting up Vue.js. I created a new directory /mixins with a new file api.js. I want to use that as mixin so that every component can use a function to access my api. But I don't know how to do it.

This is my /mixins/api.js file:

export default{
  callapi() {
    alert('code to call an api');
  },
};

This is my main.js file:

import Vue from 'vue';
import VueRouter from 'vue-router';
import VueResource from 'vue-resource';

import { configRouter } from './routeconfig';

import CallAPI from './mixins/api.js';

// Register to vue
Vue.use(VueResource);
Vue.use(VueRouter);


// Create Router
const router = new VueRouter({
  history: true,
  saveScrollPosition: true,
});

// Configure router
configRouter(router);


// Go!
const App = Vue.extend(
  require('./components/app.vue')
);

router.start(App, '#app');

How can I include my mixin the right way now, so that every component has access to the callapi() function?

2

2 Answers

9
votes

You can apply mixin globally using Vue.mixin

api.js
------

export default {
  methods: {
    callapi() {};
  }
}

main.js
-------

import CallAPI from './mixins/api.js';

Vue.mixin(CallAPI)

As the documentation states you should use it carefully:

Use global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components.

13
votes

If you want to use a mixin on a specific component, rather than all components, you can do it like this:

mixin.js

export default {
  methods: {
    myMethod() { .. }
  }
}

component.vue

import mixin from 'mixin';

export default {
  mixins: [ mixin ]
}

Another thing you might consider is using a component extension design pattern i.e. creating a base component and then inheriting from that in sub components. It's a little more involved but keeps code DRY if you have many components sharing many options and perhaps inheriting the template too.

I've written about it on my blog if you're interested.