首页 课程 师资 教程 报名

从文件中获取Vue配置值

  • 2022-03-16 10:17:45
  • 1579次 星辉

从文件中获取Vue配置值要怎么做呢?

需要从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

使用VUE3,可以通过添加

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

到main.js文件。从那时起,$config可以在所有文件的模板和脚本中使用。

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交