【问题标题】:How to react to a global variable with Vue?如何使用 Vue 对全局变量做出反应?
【发布时间】:2018-12-18 21:27:23
【问题描述】:

我有一个注入了一些全局配置对象的移动 webview:

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

稍后 WebView 注入这个:

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
    }
  },
};

但是页面没有更新。如何应对变化?

P.D:我确认该对象已使用 safari 调试工具进行了更新。也可以在本地 html 中测试。

【问题讨论】:

  • 向 Vue 原型添加属性不会使其反应。为了使其具有反应性,您需要执行类似于 described here 的操作。
  • 你能把你的配置放在主 vue 实例的数据中吗?在这种情况下,vue 将不惜一切代价确保它是响应式的
  • 是的,工作。我需要访问 this.$root。请添加为答案。

标签: javascript ios vue.js uiwebview


【解决方案1】:

有3种方法可以实现你想要的

1- 确保在组件中导入 vue

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

2- 如果您不想导入 vue,您可以在任何实例中使用 proto 直接访问原型。

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

3- 由于您在原型中添加了配置,因此您实际上可以使用 this 从 vue 实例直接访问

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

无论哪种风格,你都可以选择。

但我个人建议使用第三种,因为访问实例的原型是一种反模式。

希望对你有帮助。

【讨论】:

    【解决方案2】:

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

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

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

    现在让我们看看如何在代码中做到这一点:

    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

    就是这样。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 2021-05-13
      • 2020-04-18
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多