Home

Awesome

Vue Options API Constants Plugin

Adds a constants section to your Options API components.

Under the hood the constants values are frozen (Object.freeze()) and returned as cached computed properties, accessible in the template.

Use

  1. npm install --save vue-options-api-constants-plugin
  2. Import the plugin into your main.js and then app.use it, like so:
    import { createApp } from 'vue';
    import constantsPlugin from 'vue-options-api-constants-plugin';
    
    const app = createApp({});
    app.use(constantsPlugin);
    app.mount('#app');
    
  3. In any of your Options API components, you can now add a top level constants object, like so:
    <template>
      <div>
        {{ BRAND_NAME }}
      </div>
    </template>
    
    <script>
    import { BRAND_NAME } from './constants.js';
    
    export default {
      name: 'AnExample',
      constants: {
        BRAND_NAME
      }
    };
    </script>
    

Use via CDN

<!DOCTYPE html>
<html>
  <head>
    <title>Example</title>
    <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script>
    <script src="https://unpkg.com/vue-options-api-constants-plugin@1.0.0/cdn.js"></script>
  </head>
  <body>
    <div id="app">
      {{ AN_EXAMPLE }}
    </div>
    <script>
      const AN_EXAMPLE = 'An example';

      const app = Vue.createApp({
        constants: {
          AN_EXAMPLE
        }
      });
      app.use(window.constantsPlugin);
      app.mount('#app');
    </script>
  </body>
</html>

Benefits

Why not use data, setup, computed or methods?

Downsides