Add Application Constants in VueJS

Recently I was developing a web application using VueJS, a clever javascript framework. We have had discussions at Gorges on how to choose between VueJS and ReactJS, and I liked Ted’s observation that VueJS is easier to add to existing projects.

An early question I had was how to integrate application constants into VueJS. Web applications usually need some common constants, whether they be names, sizes, or just programming flags.

The constants could be placed into a VueJS component named Constants.vue, which would look something like this:

// Constants.vue
export default {
  BUCKET: "s3-custom-images",
  VERSION: 1.5,
  EXT_LINK: "https://link.tld"

Admittedly this could instead be converted to a Javascript-only file named Constants.js. In other components or views, the constants would presumably be used like this:

<p> Version: {{ Constants.VERSION }} </p>
import Constants from "@/components/Constants";

This is acceptable, but the component would need to be referenced and loaded in every component. I later learned that a plugin would be easier.

Here is how a plugins/Constants.js file would look:

// plugins/Constants.js
let Constants = {
  //  install
  install(Vue, options) {
    //  create global Constants
    Vue.Constants = {
      BUCKET: "s3-custom-images",
      VERSION: 1.5,
      EXT_LINK: "https://link.tld"

export default Constants;

In my main.js file, I load the constants just once like this:

// main.js
import Constants from "@/plugins/Constants";


And reference these constants in various components:

Version: {{ Vue.Constants.VERSION }}

There are probably dozens of ways to have accomplished this goal of referencing application-referencing wide constants in a VueJS program, but this approach seemed straightforward, easy, and intuitive.


Need help building a web application?
Read more about our Web Development services

Written by Matt Clark


GORGES Web Development The owner of this website has made a commitment to accessibility and inclusion, please report any problems that you encounter using the contact form on this website. This site uses the WP ADA Compliance Check plugin to enhance accessibility.