问题
I'm developing a couple of Vue apps using single file components. I find quite a few of my components require common config information, for example an object containing delivery methods which I might define like this:
const DeliveryMethods = {
DELIVERY: "Delivery",
CARRIER: "Carrier",
COLLATION: "Collation",
CASH_AND_CARRY: "Cash and carry"
}
What would be the neatest and simplest way to make that available to my components? At the moment, I have done it with a file 'config.js', as below:
export default {
DeliveryMethods: {
DELIVERY: "Delivery",
CARRIER: "Carrier",
COLLATION: "Collation",
CASH_AND_CARRY: "Cash and carry"
}
}
In my components where I need it, I have import config from 'src/config.js', and where I want to use one of these, I'll refer to e.g., config.DeliveryMethods.CASH_AND_CARRY. This seems to me rather long-winded and repetitive, though, and I'd prefer to be able to use just DeliveryMethods.CASH_AND_CARRY instead of config.DeliveryMethods.CASH_AND_CARRY. What do others use to accomplish this?
回答1:
delivery-methods/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
}
Usage
import DeliveryMethods from './path/to/delivery-methods'
console.log(DeliveryMethods.CARRIER)
Or:
config.js
export default Object.freeze({
DELIVERY: "Delivery",
CARRIER: "Carrier",
COLLATION: "Collation",
CASH_AND_CARRY: "Cash and carry"
})
Usage:
import DeliveryMethods from './path/to/delivery-methods'
console.log(DeliveryMethods.CARRIER)
回答2:
Thanks, this and subhaze's comment pointed me in the right direction. DeliveryMethods isn't the only constant I'd want to use, so export default doesn't work if I want to have all my constants in a single file for ease of maintenance. What I've done is this:
export const DeliveryMethods = {
DELIVERY: "Delivery",
CARRIER: "Carrier",
COLLATION: "Collation",
CASH_AND_CARRY: "Cash and carry"
};
In my components I have import {DeliveryMethods} from 'src/config.js', which allows me to simply use e.g. DeliveryMethods.COLLATION. I can export/import any number of constants clearly and simply. Still feeling my way round Javascript modules!
LATER: Following WaldemarIce's suggestion, I have changed this to:
export const DeliveryMethods = Object.freeze({
DELIVERY: "Delivery",
CARRIER: "Carrier",
COLLATION: "Collation",
CASH_AND_CARRY: "Cash and carry"
});
That works better.
来源:https://stackoverflow.com/questions/47597384/best-way-to-define-common-constants-in-vue-js