607.273.3828

Vue and Application Constants

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";

Vue.use(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.

 
Written by Matt Clark

RECENT ARTICLES:

  • VueJS and $forceUpdate()

    August 10, 2022
    Matt ClarkMatt Clark
  • Takeaways from Networking@Rev: Empowering the Ecosystem

    July 22, 2022
    Ondine Morgan-KnappOndine Morgan-Knapp
  • Installing Greenbone for Vulnerability Assessment Scanning

    February 1, 2021
    Matt ClarkMatt Clark
  • GORGES Web Development