Vue not updating global $ prototype variable

Viewed 787

I am trying to create a global variable in Vue that I can read and update all over the application. I decided to use the prototype approach but for some reason the variable gets updated (the console.log changes) but the front end () doesn't get updated. Could someone please explain to my why this does what it does and how I can solve this "global variable" problem.

main.js:

Vue.prototype.$something = 'Hi there!';

// I tried this but it gives the same result
// Vue.prototype.$something = { text: 'Hi there!' };

component1.vue:

<label>{{$something}}</label>

component2.vue:

<label>{{$something}}</label>
<button v-on:click="changeThat()">Change</button>
...
changeThat() {
  console.log(this.$something); // 'Hi there!'
  this.$something = "Good bye!";
  console.log(this.$something); // 'Good bye!'
}

I want the two <label> to update when this.$something is changed.

1 Answers

You make use of Vue.observable like this:

Vue.prototype.$globalData = Vue.observable({
  label: 'test' 
});

In any of the components in the app, you can use it like this:

{{ $globalData.label }}

If you change the label anywhere like this:

this.$globalData.label = 'new test';

It'd reflect in all of the components.

Related