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?
- You don’t. Global variables have no place in today’s society
- 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
main.js or the file where you initiate Vue and code in the prototype.
Go to any of your views/ component and start using the prototype.
How about methods?
You can use a similar model to define a function prototype.
You can access this function using
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.
So, shall I go crazy with this?
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.