To define common constants in Vue. js, we can create a module that export an object with the constant values. const DELIVERY = "Delivery"; const CARRIER = "Carrier"; const COLLATION = "Collation"; const CASH_AND_CARRY = "Cash and carry"; export default { DELIVERY, CARRIER, COLLATION, CASH_AND_CARRY, };
You can always define a variable outside of the Vue app scope and use it throughout the application. However, if you are using any bundler like Webpack/Browserify/etc. you can do the same but you'd have to import it into every component using it.
The const keyword is used to create a constant in Vue. js.
A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events. Functions defined inside the methods object can be further called for performing actions.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With