如何在 Vue.js 中创建全局函数?

Mg *_*int 4 vue-component vuejs2

我想在我的应用程序中全局使用一些功能。
我的问题的大部分答案都参考了 Vue Mixin。虽然我使用它,但它不能解决我的问题。这是我的尝试

Vue.mixin({
    methods:{
        gFun(){
            console.log("Works");
        },
    }
})

const app = new Vue({
    el: '#app',
    data: {

    },
    created(){
        gFun();
    },
    methods: {

    }
});
Run Code Online (Sandbox Code Playgroud)

Vue 说“ReferenceError: testMixin 未定义”。
我想要的只是能够全局使用gFun()(而不是像this.gFun()那样使用)。请解释我的东西。
是否使用 Vue Mixin 都可以。

Sol*_*lar 9

一种方法是使用您建议的 Vue mixins。另一个很好的方法是使用Plugin

请注意我如何声明它们以及我如何调用两个全局变量之间的差异,尤其是插件选项中的美元符号 ($)。无论this.gMixinFun()this.$gPluginFun()将作为在Vue公司的实例选项全局方法。

Vue.config.productionTip = false;
Vue.config.devtools = false;


// OPTION 1: Using Mixin
Vue.mixin({
  methods: {
    gMixinFun: function() {
      return "this is a mixin test"
    }
  }
});

// OPTION 2: Using plugin
const plugin = {
  install() {
    Vue.gPluginFun = () => 'this is a plugin test' //Vue.gPluginFun()
    Vue.prototype.$gPluginFun = () => 'this is a plugin test' //this.$gPluginFun()
  }
}

Vue.use(plugin)

const app = new Vue({
  el: '#app',
  created() {
    console.log("Using mixins =>", this.gMixinFun());
    console.log("Using plugins =>", this.$gPluginFun()); //or you can use Vue.gPluginFun() without the dollar($) sign
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
</div>
Run Code Online (Sandbox Code Playgroud)


sma*_*c89 2

这对于 Vue 来说不是问题。

您可以使用以下方法在 javascript 中创建全局函数:

window.gFun = window.gFun || () => console.log("Works");
Run Code Online (Sandbox Code Playgroud)