Apply global variable to Vuejs
Asked Answered
C

11

110

I have a javascript variable which I want to pass globally to Vue components upon instantiation thus either each registered component has it as a property or it can be accessed globally.

Note:: I need to set this global variable for vuejs as a READ ONLY property

Cytaster answered 30/11, 2016 at 19:7 Comment(1)
for VUE-3 see the below answers.Encyclical
T
136

Just Adding Instance Properties

vue2

For example, all components can access a global appName, you just write one line code:

Vue.prototype.$appName = 'My App'

Define that in your app.js file and IF you use the $ sign be sure to use it in your template as well: {{ $appName }}

vue3

app.config.globalProperties.$http = axios.create({ /* ... */ })

$ isn't magic, it's a convention Vue uses for properties that are available to all instances.

Alternatively, you can write a plugin that includes all global methods or properties. See the other answers as well and find the solution that suits best to your requirements (mixin, store, ...)

Todo answered 16/6, 2017 at 2:5 Comment(6)
where to define it ?Horsetail
but i can't get it's value inside data function. How can i do it? I've set my var like this, it read it fine at other methods, but data don't.Selfridge
Important: There may be data/utilities you’d like to use in many components, but you don’t want to pollute the global scope.Aegyptus
When you change this at some point with this.$appName = 'Changed' then the other components don't notice this change. How do you change this global variable?Loveinidleness
in v-for loop it display 'undefined'Columbic
@Loveinidleness use vuex instead for that caseOvermatter
S
120

You can use a Global Mixin to affect every Vue instance. You can add data to this mixin, making a value/values available to all vue components.

To make that value Read Only, you can use the method described in this Stack Overflow answer.

Here is an example:

// This is a global mixin, it is applied to every vue instance. 
// Mixins must be instantiated *before* your call to new Vue(...)
Vue.mixin({
  data: function() {
    return {
      get globalReadOnlyProperty() {
        return "Can't change me!";
      }
    }
  }
})

Vue.component('child', {
  template: "<div>In Child: {{globalReadOnlyProperty}}</div>"
});

new Vue({
  el: '#app',
  created: function() {
    this.globalReadOnlyProperty = "This won't change it";
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
  In Root: {{globalReadOnlyProperty}}
  <child></child>
</div>
Scion answered 30/11, 2016 at 20:33 Comment(3)
In JS code of a child component, use like this, this.globalReadOnlyProperty.Annuity
Wow, you really saved my bacon! I owe you bigtime! For real though this is greatDiscretion
Why is this available to my component in the template but not in my mounted function? axios.get(API_URL + '/videos')Earwax
F
26

In VueJS 3 with createApp() you can use app.config.globalProperties

Like this:

const app = createApp(App);

app.config.globalProperties.foo = 'bar';

app.use(store).use(router).mount('#app');

and call your variable like this:

app.component('child-component', {
  mounted() {
    console.log(this.foo) // 'bar'
  }
})

doc: https://v3.vuejs.org/api/application-config.html#warnhandler

If your data is reactive, you may want to use VueX.

Foxy answered 29/10, 2020 at 11:43 Comment(1)
How do I write this: app.component('child-component', {.... in a component?Miscellany
A
6

You can use mixin and change var in something like this.

// This is a global mixin, it is applied to every vue instance
Vue.mixin({
  data: function() {
    return {
      globalVar:'global'
    }
  }
})

Vue.component('child', {
  template: "<div>In Child: {{globalVar}}</div>"
});

new Vue({
  el: '#app',
  created: function() {
    this.globalVar = "It's will change global var";
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
  In Root: {{globalVar}}
  <child></child>
</div>
Alysiaalyson answered 22/10, 2018 at 11:54 Comment(2)
Hello, it doesnt changeSexagesimal
@harmoniuscool it wouldn't change because for every component the data is created anew, that's why data: is a function. So the above example by @amin provides a copy of the global value, and nor does his example demonstrate that it could be changed. If you want mutable global variables and state, then you should use Vuex really.Teahan
B
2

If the global variable should not be written to by anything, including Vuejs, you can use Object.freeze to freeze your object. Adding it to Vue's viewmodel won't unfreeze it. Another option is to provide Vuejs with a frozen copy of the object, if the object is intended to be written globally but just not by Vue: var frozenCopy = Object.freeze(Object.assign({}, globalObject))

Banwell answered 5/3, 2019 at 8:55 Comment(0)
G
2

you can use Vuex to handle all your global data

Garrido answered 13/2, 2020 at 14:17 Comment(0)
S
2

In your main.js file, you have to import Vue like this :

import Vue from 'vue'

Then you have to declare your global variable in the main.js file like this :

Vue.prototype.$actionButton = 'Not Approved'

If you want to change the value of the global variable from another component, you can do it like this :

Vue.prototype.$actionButton = 'approved'

https://v2.vuejs.org/v2/cookbook/adding-instance-properties.html#Base-Example

Shantay answered 12/11, 2020 at 4:47 Comment(0)
H
2

If you’d like to use a variable in many components, but you don’t want to pollute the global scope. In these cases, you can make them available to each Vue instance by defining them on the Vue prototype:

Vue.prototype.$yourVariable = 'Your Variable'

Please remember to add this line before creating your Vue instance in your project entry point, most of time it's main.js

Now $yourVariable is available on all Vue instances, even before creation. If we run:

new Vue({
  beforeCreate: function() {
    console.log(this.$yourVariable)
  }
})

Then "Your Variable" will be logged to the console!

doc: https://v2.vuejs.org/v2/cookbook/adding-instance-properties.html#Base-Example

If you want to make this variable immutable, you can use the static method Object.defineProperty():

Object.defineProperty(Vue.prototype, '$yourVariable', {
  get() {
    return "Your immutable variable"
  }
})

This method by default will prevent your variable from being removed or replaced from the Vue prototype

If you want to take it a step further, let's say your variable is an object, and you don't want any changes applied to your object, you can use Object.freeze():

Object.defineProperty(Vue.prototype, '$yourVariable', {
  get() {
    return Object.freeze(yourGlobalImmutableObject)
  }
})
Huron answered 2/9, 2021 at 6:6 Comment(0)
S
0

A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY. I did like that:

Supposing that I have 2 global variables (var1 and var2). Just add to the index.html header this code:

  <script>
      function getVar1() {
          return 123;
      }
      function getVar2() {
          return 456;
      }
      function getGlobal(varName) {
          switch (varName) {
              case 'var1': return 123;
              case 'var2': return 456;
              // ...
              default: return 'unknown'
          }
      }
  </script>

It's possible to do a method for each variable or use one single method with a parameter.

This solution works between different vuejs mixins, it a really global value.

Salute answered 20/6, 2020 at 12:10 Comment(0)
T
0

in main.js (or any other js file)

export const variale ='someting' in app.vue (or any other component)

import {key} from '../main.js' (file location) define the key to a variable in data method and use it.

Titanate answered 1/7, 2021 at 21:1 Comment(1)
This does not make it a global variable.Pomeroy
J
0

Simply define it in vite configuration

export default defineConfig({
    root:'/var/www/html/a1.biz/admin',  
    define: {
       appSubURL: JSON.stringify('/admin')
    }, ..../// your other configurations 
});

Now appSubURL will be accessible everywhere

Judicature answered 27/9, 2022 at 3:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.