Global Variables and Functions in Vue

Vue provides a way to create global variables and functions using Vue.prototype.

What do you normally do if you want to create a global variable in Vue?

  1. You don’t. Global variables have no place in today’s society
  2. You create variables in storage. That’s the purpose of storage

You can say the exact same thing about functions.

But, what if you have variables that sound silly if they get into something as elegant as Vuex store? Or worse, what if you don’t have a store and you cannot add one since you inherited a stupid-ass Vue project?

Well, fear not - Vue.prototype is here. Vue prototypes (or instance props) help you keep the scope comparatively clean and still use a few variables (or functions) globally.

Let’s take a simple use case to store server API URL as a global variable. You do two things -

Introduce the prototype

Go to main.js or the file where you initiate Vue and code in the prototype.

// main.js
import Vue from "vue";
import App from "./App.vue";

Vue.prototype.$apiURI = "/api";

new Vue({
  render: h => h(App)
}).$mount("#app");
Use prototype

Go to any of your views/ component and start using the prototype.

<!-- myAwesomeView -->

<script>
  export default {
    mounted() {
      console.log("apiURI", this.apiURI);
    }
  };
</script>

How about methods?

You can use a similar model to define a function prototype.

// main.js
Vue.prototype.$funkyLog = function(x) {
  console.log(x);
};

You can access this function using this.$funkyLog('logMessage'), where logMessage may be a data variable, computed element or a prop in the component.

The beauty of this function is in getting access to the current context at a global level.

// main.js
Vue.prototype.$makeItFalsy = function(it) {
  this.it = !this.it;
};

So, shall I go crazy with this?

Hmm.. no.

I have found that using prototypes only confuses people. Use plugins, global filters or Vuex stores instead.

Head over to docs to know more on Vue prototypes and instance properties.

Last updated:
Categories: Vue
Tags: VueJS
comments powered by Disqus