【问题标题】:Get config value in vue file获取vue文件中的配置值
【发布时间】:2021-11-18 03:04:56
【问题描述】:

可能是一个非常简单的问题:我需要从 vue 文件的 html 块中获取配置值。

我有这个简单的 config.js

const env = process.env.NODE_ENV

const development = {
  images: {
    server: "http://localhost:4001",
  }
}

const production = {
  images: {
    server: "http://someimageserver.com",
  }
}

const config = {
  development,
  production,
}

module.exports = config[env]

还有这个简单的 vue.js

<template>
  <div>
      <img :src="`${config.images.server}/images/someimage.jpg`"/>
  </div>
</template>

在运行时,上述抛出

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'images')

我应该怎么做才能完成这项工作? 提前致谢

注意:我可以使用从脚本块中获取配置值,例如,这非常有效

import config from "../../config"
...
var c = config.images.server

更新: 使用 vue 3,可以通过添加轻松实现这一点

import config from "../config"
app.config.globalProperties.$config = config

到 main.js 文件。从那里开始,$config 可以在所有文件的模板和脚本中使用。来源:https://v3.vuejs.org/guide/migration/global-api.html#vue-prototype-replaced-by-config-globalproperties

【问题讨论】:

    标签: vue.js node-config


    【解决方案1】:

    在 Vue 中,你需要初始化一个变量并将你导入的内容赋值给它,并最终返回这个变量。如下所示:

    Vue2:

    import config from "../../config"
    
    export default {
      data() {
        return {
          config: config
        }
      }
    }
    

    Vue3:

    import config from "../../config"
    
    export default {
      setup() {
        return {
          config
        }
      }
    }
    

    那么模板中的url应该可以正常工作了。

    --------------更新---------- --

    如果要全局使用config,可以注册为Plugin。

    创建 plugin.js

    import config from "../../config"
    
    export const Config = {
      install(Vue, options) {
        Vue.prototype.$config = function() {
          return config
        }
      }
    }
    

    然后,在你的 main.js 中,添加以下代码

    import * as Plugins from '@/plugin.js'
    
    Vue.use(Plugins.Config.install)
    

    然后您可以在模板中使用$config,例如$route,而无需任何其他导入。当然,您可以在plugin.js 中编写其他全局函数,并将它们中的每一个注册到main.js

    【讨论】:

    • 感谢您的帮助。我已经知道该怎么做了。我们的想法是不使用这种技术。例如,使用 vue-router,可以在模板中使用 $route。是否可以对 node-config 做同样的事情? $config ?
    • @jhfelectric 你可以像这样使用 $route 因为 vue-router 使用插件。所以我猜你想编写自己的插件并在全球范围内使用 $config 吗?我更新了我的答案,想知道这是否是你所坚持的。
    • 再次感谢。我使用 vue3 样式全局添加了配置: import config from "../config"; app.config.globalProperties.$config = 配置;效果很好。尽管如此,令我惊讶的是,已经包含的任何内容都不会提供这样一种在所有文件中轻松使用配置的方式。我感谢您的回答,并用我的解决方案更新了我最初的问题。
    • @jhfelectric 感谢您的信任。我很高兴你解决了你的问题!
    猜你喜欢
    • 2023-03-14
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多