Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a global variable in Vue.js

In Vue.js 0.12, it was easy enough to pass a variable from the root component all the way down to its children: you just use inherit: true on any component that requires the data of its parent.

Vue.js 1.0 removed the ability to use inherit: true. Understandably, you really shouldn't be inheriting everything everywhere all the time.

This is something of a problem upgrading from 0.12 to 1.0 however. I've got components littered with inherit, most only so that it can get the important config variable baseurl from the root component. Such a variable should definitely by known by any component that has a link in it.

<a href="{{ baseurl }}/page">Link</a>

I could pass the prop for config to every single component, but that really seems redundant and clunky.

<c0 :config="{baseurl: 'example.com'}"></c0>

<c1 :config="config"></c1>

<c2 :config="config"></c2>

<c3 :config="config"></c3>

Any good way to create a global scope for all components?

like image 764
MattyRad Avatar asked Jan 06 '23 10:01

MattyRad


2 Answers

This might not be the best solution out there, but it works and isn't too much trouble. I just set a getter prototype method.

Vue.prototype.$config = function (key) { 
  var config = this.$root.$get('config');

  if (config) {
    return config[key];
  } 

  return '';
}

<a href="{{ $config('baseurl') }}/page">Link</a>

Accessible by any component.

like image 121
MattyRad Avatar answered Jan 18 '23 14:01

MattyRad


If you're using something like webpack in your Vue setup, then you can share a variable across your project with ES6 modules / import statements.

main.js:

import Vue from 'vue'
import config from './config.js'
import thing from './thing.js'

config.setColor('green');

var vm = new Vue({
   el: "#app",
   components: { thing },
   template: '<thing></thing>'
});

config.js:

var color = 'blue';

export default {
   getColor: function () {
      return color;
   },
   setColor: function (val) {
      color = val;
   }
}

thing.js:

import config from './config.js'

export default {
   name: 'thing',
   template: '<div>thing</div>',
   created: function () {
      console.log(config.getColor());
      // green
   }
}
like image 23
exclsr Avatar answered Jan 18 '23 14:01

exclsr