更新時間:2022-03-16 10:17:45 來源:動力節(jié)點 瀏覽1913次
從文件中獲取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可以在所有文件的模板和腳本中使用。