Using mixins with Vuejs

杀马特。学长 韩版系。学妹 提交于 2020-06-27 14:54:10

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/39358448/using-mixins-with-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!