In this post, you will be introduced to using prototypes in Vue.js to access properties globally instead of using multiple imports in your workflow.
Before you start…
This post is suited for developers of all stages, including beginners. Here are a few things you should already have before going through this tutorial:
- Node.js version 10.x and above installed. You can verify whether you do by running the command below in your terminal/command prompt:
node -v
- A code editor — I highly recommend Visual Studio Code
- Vue’s latest version, installed globally on your machine
- Vue CLI 3.0 installed on your machine. To do this, uninstall the old CLI version first:
npm uninstall -g vue-cli
Then, install the new one:
npm install -g @vue/cli
- Download a Vue starter project here
- Unzip the downloaded project
- Navigate into the unzipped file and run the command below to keep all the dependencies up to date:
npm install
How imports help us access files
While working in your Vue project, the fastest way to access a new component in another one or a nested one is simply by importing the needed component or resource.
This can easily become inefficient, however, since you will have to repeat import statements and even register components for each import (if they are components). Luckily, Vue provides a more efficient way to handle this for cases in which you have globally defined a data object or an incoming HTTP request.
Vue.prototype
To create a global property in your Vue application and then access it through a property statement instead of an import statement, Vue provides a platform we call prototypes. This way, you define the global property or data object, telling Vue to remember it as one, and then access it in any component with just a line of code.
Prototype syntax
The definition of a Vue prototype in your main JavaScript file will look like this:
Vue.prototype.$blogName = ‘LogRocket’
Here, blogName
is the property or data name and the LogRocket
string is the value. With this definition, Vue.js gets this property (the blog name, in our case) available to every Vue instance in the entire project even before the instance is created.
The $
sign
The $
sign is used in Vue.js to identify properties that can be used in all available instances in any given Vue project. This distinction was made due to conflicts relating to property name definitions and access. With the $
sign, there is a clear difference between properties and global properties available to all instances.
Demo
To follow through with this section, you must have read this post from the start, downloaded the starter project from the link above, and opened it up in VS Code. To illustrate the syntax example in the section above, open up your main.js
file and add the prototype definition so the whole file looks like this:
import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false Vue.prototype.$blogName = 'LogRocket' new Vue({ render: h => h(App), }).$mount('#app')
Now that you have defined a property name, open your root component and copy in the code block below:
<template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png"> <Test msg="Welcome to Your Vue.js App"/> </div> </template> <script> import Test from './components/Test.vue' export default { name: 'app', components: { Test }, beforeCreate: function() { console.log(this.$blogName) } } </script>
Here you can see that the beforeCreate
lifecycle hook method was used to validate the instantiation claims about Vue prototypes. If you run the application in your dev server, you will see the saved name (LogRocket) displayed in your browser console.
Some Vue prototype use cases
A lot of data values, properties, and utilities like HTTP resources can be made global properties with Vue prototypes. In this section, I will introduce a few of them.
Functions as prototypes
Vue.js allows you to add not only properties, but also methods as prototypes. With that, every instance in which the prototype is used gets access to the logic set up in the prototype definition.
This includes access to using this
to access data, computed properties, and even other methods inside any Vue instance in the project. A quick example can be to use a string reversal function. In your main.js
file, add the new prototype under the old one:
Vue.prototype.$reverseString = function(x) { this[x] = this[x] .split('') .reverse() .join('') }
Copy the code block below into your app.vue
file:
<template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png"> <Test msg="Welcome to Your Vue.js App"/> </div> </template> <script> import Test from './components/Test.vue' export default { name: 'app', components: { Test }, data() { return { msg: 'LogRocket' } }, beforeCreate: function() { console.log(this.$blogName) }, created: function() { console.log(this.msg) this.$reverseString('msg') console.log(this.msg) } } </script>
Here, the created lifecycle hook was used to log the reverseString
function, and if you run your application in the dev server, you will see that LogRocket is printed in reverse.
Prototypes for imports
If your application has communications with a third API, you will normally have to import Axios on each component you want to make a get
request from. Here is a quick illustration — open a new terminal in your VS Code application and install Axios:
npm install axios
Now, head to your app.vue
file where you want to make a get
request, and copy this code block inside:
<template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png"> <Test msg="Welcome to Your Vue.js App"/> <div v-for="user in users" :key="user.id"> <p>{{user.name}}</p> </div> </div> </template> <script> import Test from './components/Test.vue' import axios from 'axios' export default { name: 'app', components: { Test }, data() { return { msg: 'LogRocket', users: [] } }, created: function (){ axios.get('https://jsonplaceholder.typicode.com/users') .then(res => { this.users = res.data; }) } , beforeCreate: function() { console.log(this.$blogName) } } </script>
You will notice that for every component from which you want to make a get request, you will have to repeat this import statement. To solve this, Vue lets you use the prototype feature to import once and in any Vue instance in your project.
Open your main.js
file and copy the code block below inside it:
import Vue from 'vue' import App from './App.vue' import axios from 'axios' Vue.config.productionTip = false Vue.prototype.$blogName = 'LogRocket' Vue.prototype.$reverseString = function(x) { this[x] = this[x] .split('') .reverse() .join('') } Vue.prototype.$axios = axios new Vue({ render: h => h(App), }).$mount('#app')
In your app.vue
file, delete the import statement and use the $axios
alias you already created, like this:
<script> import Test from './components/Test.vue' export default { name: 'app', components: { Test }, data() { return { msg: 'LogRocket', users: [] } }, created: function (){ this.$axios.get('https://jsonplaceholder.typicode.com/users') .then(res => { this.users = res.data; }) } , beforeCreate: function() { console.log(this.$blogName) } } </script>
You can find the complete code to this tutorial here on GitHub.
Conclusion
You have now been introduced to the concept of using prototypes in Vue to make properties globally available to all Vue instances in your project. You were also shown the advantages of using prototypes, including, but not limited to, a more efficient workflow. Happy hacking!
Experience your Vue apps exactly how a user does
Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.
The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.
Modernize how you debug your Vue apps - Start monitoring for free.
The prototype member is not provided by Vue, it’s a basic JS language pattern. What this post suggests is generally called “monkey patching”. It’s quite convenient, but might break future implementations of the Vue object.
If you really needed this you could consider namespacing: Extend the prototype by an object with a unique name which is unlikely to get implemented by others. Then add your extensions inside that object.
Fully agree with this. Rather than saturating vue’s prototype with a heap of clutter, choose a single $ prefixed namespace and then dump all your extensions under that.
EG:
vue.prototype.$myextension = {}
vue.prototype.$myextension.$axios = …
etc
Otherwise, even with namespacing if you saturate the top level of the prototype, you’re bound to run into a collision eventually.
Hi, this is very interesting. I have a question. I am developing dynamic content via templates at runtime.
What this does is to receive any template, however those with bindings don’t work as it gives a ref error. How can I make this be able to see the ‘global’ state in the ‘$data’ attribute. For example my template might have {{ number }}, currently im getting number undefined. So I just want the component to have access to the global state to pick this up.
Vue.component(“renderstring”, {
props: {
string: {
required: true,
type: String
}
},
render(h) {
const self = this
console.log(this.$data)
const render = {
template: “” + this.string + “”,
}
return h(render)
}
})
Thanks a lot. #FoundThisCodeOnTheNet
Is it possible to change a Vue.prototype value after it has been defined?