如何使用 Vue 对全局变量做出反应?

How to react to a global variable with Vue?

我有一个注入了一些全局配置对象的移动 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.

中测试

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

嗯,你可以选择任何适合你的风格。

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

希望对您有所帮助。

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

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 都会对其做出反应。

现在让我们看看如何用代码实现:

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.

好吧,就是这样。

希望对您有所帮助。