如何使用 Vue 对全局变量做出反应? [英] How to react to a global variable with Vue?

查看:31
本文介绍了如何使用 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"
}

稍后 WebView 注入此内容:

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"
}

并尝试将其用于组件:

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:我确认该对象已使用 safari 调试工具更新.也在本地 html 中测试.

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

推荐答案

您实际上可以将其作为数据选项添加到主 vue 实例中,而不是将配置放入 Vue 的原型中,这将保证您所有的配置属性将是反应性的.如文档中所述

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

当您将普通 JavaScript 对象作为其数据选项传递给 Vue 实例时,Vue 将遍历其所有属性并使用 Object.defineProperty 将它们转换为 getter/setter.

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.

话虽如此,每当您更新配置属性时,vue 都会对其做出反应.

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"
        } 
    }
}

现在,无论何时您需要访问您的配置,您都可以使用 $root 从任何组件直接访问它.像 this.$root.configServer.

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

好吧.

希望能帮到你.

这篇关于如何使用 Vue 对全局变量做出反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆