Accessing properties globally in Vue.js with prototypes

Accessing properties globally in Vue.js with prototypes

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
  • Node.js version 10.x and above installed. You can verify whether you do by running the command below in your terminal/command prompt:
npm uninstall -g vue-cli
  • Node.js version 10.x and above installed. You can verify whether you do by running the command below in your terminal/command prompt:
npm install -g @vue/cli
  • Node.js version 10.x and above installed. You can verify whether you do by running the command below in your terminal/command prompt:
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 arecomponents). 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 = this
    .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 = this
    .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!

Recommended Reading

Dockerizing a Vue Application

Building simple chat web app using Vue.js and Firebase

Build Firestore Database CRUD Web App using Vue.js and Firebase

How to deploy your Vue app with Netlify

Top 10 Tips For New Vue.js Developers

MEVN Stack Tutorial With Example From Scratch

Using Renderless Components in Vue.js

Accessing the virtual DOM using render functions in Vue JS

vue-js javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

8 Popular Websites That Use The Vue.JS Framework

In this article, we are going to list out the most popular websites using Vue JS as their frontend framework. Vue JS is one of those elite progressive JavaScript frameworks that has huge demand in the web development industry. Many popular websites are developed using Vue in their frontend development because of its imperative features.

What are the differences between the various JavaScript frameworks? E.g. Vue.js, Angular.js, React.js

What are the differences? Do they each have specific use contexts?

Ember.js vs Vue.js - Which is JavaScript Framework Works Better for You

In this article we will discuss full details and comparison of both Ember.js and Vue.js

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.