Mg Mg Tint
Mg Mg Tint

Reputation: 243

How to create global functions in Vue.js?

I would like to use some functions globally in my app.
Most of the answers for my question refer to Vue Mixin. Although I use it, it cant solve my problem. This is my try

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

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

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

    }
});

Vue says "ReferenceError: testMixin is not defined".
I want is just to able to use gFun() globally(not using like this.gFun()). Please explain my something.
Using Vue Mixin or not is ok.

Upvotes: 7

Views: 11508

Answers (3)

Solar
Solar

Reputation: 1015

One way to go about it is by using the Vue mixins you suggested. Another great way to go about that is by using Plugin.

Notice how I declared them and the difference between how I called the two global variables, especially the dollar sign($) in the plugin option. Both this.gMixinFun() and this.$gPluginFun() will be available as global method in the Vue instance Options.

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
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
</div>

Upvotes: 14

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You could declare your global function like function functon_name(parameters){...}, try to pass the vue instance like a parameter in order to access its properties inside the global function as follows

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

window.gFun = function(vm) {
  console.log(vm.message);
}


const app = new Vue({
  el: '#app',
  data: {
    message: "Hello !"
  },
  created() {
    gFun(this);
  },
  methods: {

  }
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">

</div>

Upvotes: 1

smac89
smac89

Reputation: 43098

This is not a problem with Vue.

You can create global functions in javascript using something like:

window.gFun = window.gFun || () => console.log("Works");

Upvotes: 2

Related Questions