Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canonical way to define common constants in Vue.js? [closed]

Tags:

vue.js

People also ask

How do you define a constant in Vue?

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, };

How will you create constants accessible to the entire application in Vue JS?

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.

What keyword is used for generating a constant in Vue JS?

The const keyword is used to create a constant in Vue. js.

What is Vue JS methods?

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.