在 Vue.js 中包含全局函数 [英] Include global functions in Vue.js

查看:36
本文介绍了在 Vue.js 中包含全局函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Vue.js 应用程序中,我想要一些全局函数.例如一个 callApi() 函数,我可以在每次需要访问我的数据时调用它.

In my Vue.js application I want to have some global functions. For example a callApi() function which I can call every time I need access to my data.

包含这些函数以便我可以在所有组件中访问它们的最佳方法是什么?

What is the best way to include these functions so I can access it in all my components?

  • 我应该创建一个文件 functions.js 并将其包含在我的 main.js 中吗?
  • 我应该创建一个 Mixin 并将其包含在我的 main.js 中吗?
  • 还有更好的选择吗?

推荐答案

你最好的选择是插件,它可以让你向全局 vue 系统添加功能.

Your best bet would be a Plugin, which lets you add features to the global vue system.

[来自 vuejs 文档]

MyPlugin.install = function (Vue, options) {

// 1. add global method or property
Vue.myGlobalMethod = ...

// 2. add a global asset
Vue.directive('my-directive', {})

// 3. add an instance method
Vue.prototype.$myMethod = ...

}

然后你只需添加

Vue.use(MyPlugin)

在调用函数之前在代码中.

in your code before calling your function.

Vue.myGlobalMethod(parameters);

或者你的情况

Vue.callApi(parameters);

这篇关于在 Vue.js 中包含全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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