在 Vuejs 中使用 mixins [英] Using mixins with Vuejs

查看:31
本文介绍了在 Vuejs 中使用 mixins的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习如何使用 Vuejs 开发应用.我有一个 main.js 文件,其中包含用于设置 Vue.js 的代码.我用新文件 api.js 创建了一个新目录/mixins.我想将其用作 mixin,以便每个组件都可以使用一个函数来访问我的 api.但我不知道该怎么做.

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.

这是我的 /mixins/api.js 文件:

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

这是我的 main.js 文件:

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');

我现在如何以正确的方式包含我的 mixin,以便每个组件都可以访问 callapi() 函数?

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

推荐答案

你可以使用 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:

少而谨慎地使用全局 mixins,因为它会影响创建的每个 Vue 实例,包括第三方组件.

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

这篇关于在 Vuejs 中使用 mixins的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆