how to create a global variable in vue
Open your Vue.js project.
Inside the
src
folder, locate or create a file namedmain.js
.In the
main.js
file, import Vue and create a new Vue instance.
import Vue from 'vue';
import App from './App.vue';
- Declare a global variable using the Vue prototype.
Vue.prototype.$globalVariable = 'YourValue';
Replace 'YourValue'
with the desired initial value of your global variable.
- Mount the Vue instance.
new Vue({
render: h => h(App),
}).$mount('#app');
- Access the global variable in any component.
export default {
name: 'YourComponent',
mounted() {
console.log(this.$globalVariable);
},
};
Now, you can use $globalVariable
across different components in your Vue.js project.