How to useVue Prototype in Vue

In this approach, we will use the Vue.prototye.$gVar to define the global variable that is accessed in the entire application. There is an input box and button through which the updation and application of the global variable will be managed.

Syntax:

Vue.prototype.$globalVariable = 'initialValue';

Example: Below is the implementation of the above-discussed approach.

HTML




<!DOCTYPE html>
<html>
 
<head>
  <title>Example 1</title>
  <script src=
"https://cdn.jsdelivr.net/npm/vue@2">
  </script>
  <style>
    body {
      font-family: 'Arial',
                    sans-serif;
      text-align: center;
      margin: 50px;
    }
 
    input {
      padding: 10px;
      margin-bottom: 20px;
    }
 
    button {
      padding: 10px 20px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
  </style>
</head>
 
<body>
  <h1 style="color: green;">
    w3wiki
  </h1>
  <h3>
    Approach 1: Using
    Vue.prototype
  </h3>
  <div id="app">
    <h2>{{ message }}</h2>
    <input v-model="gVar"
           placeholder="Enter a
                        global variable">
    <button @click="updateGVar">
      Apply Global Variable
    </button>
  </div>
  <script>
    Vue.prototype.$gVar = '';
    new Vue({
      el: '#app',
      data: {
        message:
        'This is Global Variable ',
        gVar: ''
      },
      methods: {
        updateGVar() {
          this.$gVar = this.gVar;
          this.message =
            `Global Variable Updated:
            ${this.$gVar}`;
        }
      }
    });
  </script>
</body>
 
</html>


Output:

How to Add or Apply Global Variables in VueJS ?

In Vue.js, we can have global variables that are applied by attaching them to the Vue instance prototype. These are accessible throughout the components of the application. This is helpful for data management and sharing. In this article, we will see the two different approaches to adding or applying global variables in VueJS with practical examples.

Table of Content

  • Using Vue Prototype
  • Using Vue.mixin

Similar Reads

Approach 1: Using Vue Prototype

In this approach, we will use the Vue.prototye.$gVar to define the global variable that is accessed in the entire application. There is an input box and button through which the updation and application of the global variable will be managed....

Approach 2: Using Vue.mixin

...