Hardcoded values make a developer’s job hectic if these are repeated at several places in the codebase. That is why constants are an indispensable part of an application. It’s easy and intuitive to keep your application constants in a separate file and import them in other files to use.

Vue Js Constants
import constants from 'path_to_file/constants.js'

But what when your constants reside on the backend and you need to get them by making an ajax request to the server. how would you make sure that these constants are available before any of your components get rendered? Should we write the received constants object into a file and then export it. It doesn’t sound like a real solution. Of course, it is not.

Object Prototype

So let’s approach it with a real-world solution. First, we need to understand function constructor and its prototype. In javascript, each object created using a function constructor has access to its prototype.

/** 
 * A function to create other objects. We captialize its name to distinguish 
 * it from other normal functions.
 */
function Person(firstname) {
  this.firstname = firstname;
}


// Add a property to its prototype
Person.prototype.printFirstName = function() {
  console.log(this.firstname);
}

// Create two different objects using the function as constructor
let person1 = new Person('Munish')
let person2 = new Person('John')

Since person1 and person2 are created using a function constructor so it has access to the printFirstName method.

person1.printFirstName()   // Munish
person2.printFirstName() // John

Vue Instance Prototype

We will use the same concept by fetching our constants object from backend and then putting it into Vue prototype. So that each component in our application has access to this property.

axios.get('http://SERVER_ADDRESS/getConstants')
.then(function(res) {

  Vue.prototype.$constants = res.body.data;
  // Initialize the main instance once you receive the constants from backend
  new Vue({
    el: '#app'
  })

});

Now you can access this constant object in any of your Vue components using the following syntax

this.$constants.someConstant

Note:

Make sure your getConstants API doesn’t do any heavy lifting other than returning your constants. Because the front end application will not get bootstrapped until it responds back.