• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

[复制链接]
菜鸟教程小白 发表于 2022-12-13 04:33:08 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我有一个注入(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 中测试。



Best Answer-推荐答案


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

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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap