PASSWORD RESET

Your destination for complete Tech news

Vue

How to declare a global variable in Vue JS?

383 0
< 1 min read

In Vue, you can declare a global variable by attaching it to the Vue instance. You can do this using the Vue.prototype object.

Here’s an example of how to declare a global variable in Vue:

// main.js

import Vue from 'vue';
import App from './App.vue';

Vue.prototype.$myGlobalVariable = 'Hello World';

new Vue({
  render: (h) => h(App),
}).$mount('#app');

In this example, we’ve attached a global variable called $myGlobalVariable to the Vue instance using the Vue.prototype object. We can now access this variable in any component of our application by using this.$myGlobalVariable. For example:

<template>
  <div>
    <p>{{ $myGlobalVariable }}</p>
  </div>
</template>

<script>
export default {
  mounted() {
    console.log(this.$myGlobalVariable); // output: "Hello World"
  },
};
</script>

In this example, we’re accessing the $myGlobalVariable variable in the template using the $ shorthand for accessing Vue instance properties. We’re also logging the value of the variable to the console when the component is mounted.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.