How to react to a global variable with Vue?

让人想犯罪 __ 提交于 2020-08-03 03:25:23

问题


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.


回答1:


Instead of putting the config into the prototype of Vue, you can actually add it as a data option inside the main vue instance which will guarantee you that all your config properties will be reactive. As mentioned in the docs

When you pass a plain JavaScript object to a Vue instance as its data option, Vue will walk through all of its properties and convert them to getter/setters using Object.defineProperty.

Having said that whenever you update your config properties, vue will react to it.

Now let's see how to do it in code:

new Vue(){
    data:{ //only place where data is not a function
        configServer = {
              MODE: "DEBUG",
              isMobile: false,
              injected: false,
              version: -1,
              title:"App",
              user: null,
              host: "http://127.0.0.1:8080"
        } 
    }
}

Now whenever you need to access your config you can directly access it from any component using $root. Like this.$root.configServer.

Well that's it.

I hope it helps.




回答2:


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.



来源:https://stackoverflow.com/questions/51275301/how-to-react-to-a-global-variable-with-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!