Include global functions in Vue.js

烂漫一生 提交于 2019-11-29 00:56:58

问题


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?

  • 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?

回答1:


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

[from the vuejs Docs]

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



回答2:


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




回答3:


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

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

In main.js add 2 string

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)


来源:https://stackoverflow.com/questions/39373047/include-global-functions-in-vue-js

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