Vue and Application Constants

October 31 2019
vue

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:

    <script>
      export default {
        BUCKET: "s3-custom-images",
        VERSION: 1.5,
        EXT_LINK: "https://link.tld"
      }
    </script>

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:

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

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:

    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:

    import Constants from "@/plugins/Constants";
    Vue.use(Constants);

And reference these constants in various components:

    <template>
      <p>Version: {{ Vue.Constants.VERSION }}</p>
    </template>

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

Matt Clark

CEO / Application Developer