javascript - 如何使用 Vue 对全局变量使用react?

标签 javascript ios vue.js uiwebview

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

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

稍后 WebView 注入(inject):

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 的原型(prototype)中,您实际上可以将其作为数据选项添加到主 vue 实例中,这将保证您所有的配置属性都是响应式(Reactive)的。如文档中所述

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 都会对其使用react。

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

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

好吧,就是这样。

希望对你有帮助。

关于javascript - 如何使用 Vue 对全局变量使用react?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51275301/

相关文章:

javascript - 如何运行 jquery 下拉菜单打开/关闭

ios - 在 parse.com 的 ios 中使用 google plus 登录

css - 如何在浏览器窗口的边界(垂直和水平)中保持居中的 div?

ios - 在 iPhone X 屏幕底部获取空白区域 (Xcode 9)

vue.js - 如何保持 vue.js 单文件组件在后台加载?

vue.js - Vue : render <script> tag inside a variable (data string)

javascript - 如何使对象可作为实例和函数调用

javascript - Google Sheet 脚本有条件地将空白单元格的值设置为今天的日期,但保留现有数据相同

javascript - 使用 Jquery 和 .match() 获取 YouTube 视频 ID

php - Vue 组件未显示(Laravel 5.3)