DEV Community

Cover image for Where to put constants in a .vue file
The Jared Wilcurt
The Jared Wilcurt

Posted on • Updated on

Where to put constants in a .vue file

I often end up wishing there was a constants section in Vue, like data or methods. But something that useful will never be added into the framework, so instead I made a plugin to add it myself.

But lets explore the problem the plugin solves first:

import {
  A_CONSTANT_VALUE,
  ANOTHER_VALUE
} from '@/helpers/constants.js';

export default {
  data: function () {
    return {
      A_CONSTANT_VALUE,
      ANOTHER_VALUE
    };
  }
};
Enter fullscreen mode Exit fullscreen mode

This isn't great, because data is for reactive values that can be changed, and constants shouldn't be changed. The same problem happens if you return the constants from a setup function. So instead I could put them in computed, like so:

import {
  A_CONSTANT_VALUE,
  ANOTHER_VALUE
} from '@/helpers/constants.js';

export default {
  computed: {
    A_CONSTANT_VALUE: function () {
      return A_CONSTANT_VALUE;
    },
    ANOTHER_VALUE: function () {
      return ANOTHER_VALUE;
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

However, that ends up with a lot of boilerplate. So to get the best of both worlds, I created a Vue plugin to automate away all of that boilerplate.

Here's what the plugin lets you do

import {
  A_CONSTANT_VALUE,
  ANOTHER_VALUE
} from '@/helpers/constants.js';

export default {
  constants: {
    A_CONSTANT_VALUE,
    ANOTHER_VALUE
  }
};
Enter fullscreen mode Exit fullscreen mode

The plugin then runs the following code in every component during the beforeCreate lifecycle hook.

// Checks if the component is using the Options API and
// has a constants section
const constants = this.$options.constants;
if (constants) {
  // Create a computed property for each constant
  const computeds = {};
  Object.keys(constants).forEach(function (constantKey) {
    computeds[constantKey] = function () {
      // Freeze all non-primitives
      return Object.freeze(constants[constantKey]);
    };
  });
  // Add the computed constants to the computed
  // properties in the current component
  this.$options.computed = {
    ...this.$options.computed,
    ...computeds
  };
}
Enter fullscreen mode Exit fullscreen mode

There is one downside to this approach, some IDEs/Editors will let you ctrl+click to go from the constant in the template to its definition in the script. This breaks that functionality. Though it should be possible to allow for it, I'm just not familiar with how. So if you know how, then create a PR to improve the plugin.

Here is the plugin, so you too can use this solution:

https://github.com/TheJaredWilcurt/vue-options-api-constants-plugin

Tell your friends. Let's get this to be a normal part of Vue.

Top comments (0)