ItSolutionStuff.com

How to Define Global Variables in Vue JS?

By Hardik Savani • July 7, 2023
Vue.JS

In this example, i want to share with you how to set global variable in vue js. so you can get global variable value and use global variable in vue js. if you define global variable then you can easily access global variable in vuejs app.

We will define global variables using vue js mixin. using mixin we will declare all variables in data method. then we will use in our app vue object.

Here, we will create simple example of declaring vue js global variable. i will create "myGlobalVar" variable with some dummy text on vue js mixin. then we will use "myGlobalVar" variable in our vue js app main object and their method.

So you can see bellow full example:

Example:

<!DOCTYPE html>

<html>

<head>

<title>How to declare global variable in Vue JS? - ItSolutionStuff.com</title>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

</head>

<body>

<div id="app">

<p>Result : {{myResult}}</p>

<button @click="clickFunction()">Click Me</button>

</div>

<script type="text/javascript">

Vue.mixin({

data: function() {

return {

myGlobalVar:'this is my ItSolutionStuff.com'

}

}

})

var app = new Vue({

el: '#app',

data: {

myResult: ''

},

methods:{

clickFunction: function () {

this.myResult = this.myGlobalVar;

}

}

})

</script>

</body>

</html>

Output:

Result : this is my ItSolutionStuff.com

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Get Data Attribute Value in Vue JS?

Read Now →

How to Get Query String Parameters in Vue JS?

Read Now →

How to Download File using Axios Vue JS?

Read Now →

Vue JS Get Dropdown Selected Value Example

Read Now →

How to Get String Length in Vue JS?

Read Now →

How to Convert String to Array in Vue JS?

Read Now →

Vue JS Get Array Length or Object Length Example

Read Now →

Vue JS Call a Function On Load Example

Read Now →

Vue JS Ajax Form Submit Example Code

Read Now →

How to Get Current Date and Time in Vue JS?

Read Now →

Laravel Vue JS File Upload Using Vue-dropzone Example

Read Now →

Laravel Vue JS Axios Post Request Example

Read Now →

Laravel Vue JS Infinite Scroll Example with Demo

Read Now →

Laravel Vue JS Pagination Example with Demo

Read Now →