我正在使用单个文件组件开发一些Vue应用程序。我发现我的很多组件需要公共配置信息,例如包含传递方法的对象,我可能会这样定义:
const DeliveryMethods = {
DELIVERY: "Delivery",
CARRIER: "Carrier",
COLLATION: "Collation",
CASH_AND_CARRY: "Cash and carry"
}
将最适合我的组件的最简单方法是什么?目前,我已经使用'config.js'文件完成了它,如下所示:
export default {
DeliveryMethods: {
DELIVERY: "Delivery",
CARRIER: "Carrier",
COLLATION: "Collation",
CASH_AND_CARRY: "Cash and carry"
}
}
在我需要它的组件中,我有import config from 'src/config.js'
,我想在其中使用其中一个,我会参考例如config.DeliveryMethods.CASH_AND_CARRY
。这在我看来相当冗长和重复,我宁愿只能使用DeliveryMethods.CASH_AND_CARRY
而不是config.DeliveryMethods.CASH_AND_CARRY
。其他人用什么来实现这个目标?
答案 0 :(得分:14)
递送方法/ index.js
const DELIVERY = "Delivery"
const CARRIER = "Carrier"
const COLLATION = "Collation"
const CASH_AND_CARRY = "Cash and carry"
export default {
DELIVERY: DELIVERY,
CARRIER: CARRIER,
COLLATION: COLLATION,
CASH_AND_CARRY: CASH_AND_CARRY
}
用法
import DeliveryMethods from './path/to/delivery-methods'
console.log(DeliveryMethods.CARRIER)
或者:
config.js
export default Object.freeze({
DELIVERY: "Delivery",
CARRIER: "Carrier",
COLLATION: "Collation",
CASH_AND_CARRY: "Cash and carry"
})
用法:
import DeliveryMethods from './path/to/delivery-methods'
console.log(DeliveryMethods.CARRIER)
答案 1 :(得分:7)
谢谢,这个和subhaze的评论指出了我正确的方向。 DeliveryMethods并不是我唯一想要使用的常量,因此如果我想将所有常量放在一个文件中以便于维护,export default
就无法工作。我所做的就是:
export const DeliveryMethods = {
DELIVERY: "Delivery",
CARRIER: "Carrier",
COLLATION: "Collation",
CASH_AND_CARRY: "Cash and carry"
};
在我的组件中,我有import {DeliveryMethods} from 'src/config.js'
,这使我可以简单地使用例如DeliveryMethods.COLLATION
。我可以清楚简单地导出/导入任意数量的常量。仍然感觉我的方式围绕Javascript模块!
后来:根据WaldemarIce的建议,我已将此更改为:
export const DeliveryMethods = Object.freeze({
DELIVERY: "Delivery",
CARRIER: "Carrier",
COLLATION: "Collation",
CASH_AND_CARRY: "Cash and carry"
});
效果更好。