专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 从文件中获取Vue配置值

从文件中获取Vue配置值

更新时间:2022-03-16 10:17:45 来源:动力节点 浏览1557次

从文件中获取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可以在所有文件的模板和脚本中使用。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>