Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mixins with Vuejs

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?

like image 303
Jordy Avatar asked Nov 29 '22 22:11

Jordy


1 Answers

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.

like image 130
anthonygore Avatar answered Dec 01 '22 12:12

anthonygore