Include global functions in Vue.js

后端 未结 3 1013
抹茶落季
抹茶落季 2021-02-01 04:27

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 i

相关标签:
3条回答
  • 2021-02-01 05:00

    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)
    
    0 讨论(0)
  • 2021-02-01 05:05

    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);
    
    0 讨论(0)
  • 2021-02-01 05:18

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

    0 讨论(0)
提交回复
热议问题