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.