Javascript 在 Vue.js 中包含全局函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39373047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:31:25  来源:igfitidea点击:

Include global functions in Vue.js

javascriptvue.jsvue-resourcevue-component

提问by Jordy

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.

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

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

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

  • Should I create a file functions.js and include it in my main.js?
  • Should I create a Mixin and include it in my main.js?
  • Is there a better option?
  • 我应该创建一个文件 functions.js 并将其包含在我的 main.js 中吗?
  • 我应该创建一个 Mixin 并将它包含在我的 main.js 中吗?
  • 有更好的选择吗?

采纳答案by Justin MacArthur

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

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

[from the vuejs Docs]

[来自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 = ...

}

Then you would just add

然后你只需添加

Vue.use(MyPlugin)

in your code before calling your function.

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

Vue.myGlobalMethod(parameters);

or in your case

或者在你的情况下

Vue.callApi(parameters);

回答by Victor Bastos

Mixins can be registered globally? too. https://vuejs.org/v2/guide/mixins.html#Global-Mixin

Mixin可以全局注册吗?也。https://vuejs.org/v2/guide/mixins.html#Global-Mixin

回答by Андрей Шарунов

I have a file with function like a func.js like below

我有一个文件,其功能类似于 func.js,如下所示

export const func = {
   functionName: (data) => {
      return something  
    }
}

In main.js add 2 string

在 main.js 添加 2 个字符串

import {func} from './func.js'

Vue.prototype.$func = func

and you can use from all components if in script tag like below

如果在脚本标记中,您可以从所有组件中使用,如下所示

this.$func.functionName(somedata)

or if template tag like

或者如果模板标签像

$func.functionName(somedata)