1.0.1 • Published 2 years ago
vue-options-api-constants-plugin v1.0.1
Vue Options API Constants Plugin
Adds a constants section to your Options API components.
Use
npm install --save vue-options-api-constants-pluginImport the plugin into your
main.jsand thenapp.useit, like so:import { createApp } from 'vue'; import constantsPlugin from 'vue-options-api-constants-plugin'; const app = createApp({}); app.use(constantsPlugin); app.mount('#app');In any of your Options API components, you can now add a top level
constantsobject, 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
- The constants are frozen as computed properties under the hood, so you cannot mutate them, and if you attempt, you'll get a warning in the console.
- Gives you separation of concerns and code organization by having a place for all constants to live in each component.
Why not use data, setup, computed or methods?
dataandsetupsections would create reactive and mutatable variables, which you don't want for your constants.computedsection works, but adds a lot of boilerplate that this plugin is abstracting away for you.methodssection would have the same boilerplate as the computed, and additional boilerplate in the template ({{ AN_EXAMPLE() }}) and in the scripts (this.AN_EXAMPLE())
Downsides
- Ctrl+Click from the template to the defintion doesn't work with Intellisense/VSCode. However, this may be fixable with some editor hints, as other tools, like Vuelidate and Pinia don't have this issue. If you know how to fix this, create a PR.
- This is a plugin, so by definition it is non-standard. However, there is nothing I can do about that as Vue's core team (read: Evan) does not want this feature in Vue itself, despite it being a very common need. Perhaps, if this plugin becomes popular (tell your friends), then it would be more likely to be officially added into Vue.