Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to react to a global variable with Vue?

I have a mobile webview that is injected with some global config object:

Vue.prototype.$configServer = {
  MODE: "DEBUG",
  isMobile: false,
  injected: false,
  version: -1,
  title:"App",
  user: null,
  host: "http://127.0.0.1:8080"
}

Later the WebView inject this:

Vue.prototype.$configServer = {
  MODE: "DEBUG",
  title: "App",
  version: "2.0",
  isMobile: true,
  injected: true,
  host: "http://127.0.0.1:8081"
}

And try to use it for the component:

const HomePage = {
  key: 'HomePage',
  template: '#HomePage',
  components: { toolbar },
  data() {
    return {
      items: [
        {name:"Login", link:"login"},
      ]
    }
  },
  computed:{
    config() {
      return Vue.prototype.$configServer
    }
  },
};

However the page is not updated. How react to the change?

P.D: I confirm the object is updated with the safari debug tools. Also test in a local html.

like image 959
mamcx Avatar asked Sep 17 '25 06:09

mamcx


1 Answers

There are 3 ways to acheive what you want

1- Make sure you import vue in your component

import 'Vue' from vue
...
...
...
 computed:{
    config() {
      return Vue.prototype.$configServer
    }

2- If you don't want to import vue the you can directly access prototype using proto from any instance.

computed:{
        config() {
          return this.__proto__.$configServer
        }

3- As you have added the config in the prototype you can actually access is directly from the vue instance using this

computed:{
    config() {
      return this.$configServer
    }
  },

Well whatever style matches yours you can choose that.

But I would personally recommend using the 3rd one, because accessing the prototype of instance is sort of an anti-pattern.

I hope it helps.

like image 105
Ankit Kumar Ojha Avatar answered Sep 19 '25 19:09

Ankit Kumar Ojha