Vue.js components come with the data() function which makes anything you put in it reactive. Now, let’s assume that you have some string constants in a separate file which you want to use in a component. Importing those strings, and putting them in the return of data() function is probably not the best way to do it. That is because Vue will internally add event listeners to those variables (by assuming that they are reactive states). Thus, the app get’s a little bigger and performance hogging for no valid reason. These constants will never change their value!
//constants.js
export const myTitle = 'Night programmer';
export const myDescription = 'Hello from nightprogrammer.com!';
//App.vue
<script>
import { myTitle, myDescripion } from "./constants";
export default {
name: "App",
data() {
myTitle,
myDescription
},
};
</script>
Code language: JavaScript (javascript)
Then, what’s the right way to do it? One way I’d recommend if you have a large number of constants is to create a Vue plugin. I’ve written an article on how you can access global constants previously. As of now, I’ll show you how you can attain the same using the Component Options ($options) prototype inside the created() lifecycle method.
//App.vue
<template>
<div id="app">
<h1>
{{ $options.myTitle }}
</h1>
<h3 class="np-credits">
{{ $options.myDescripion }}
</h3>
</div>
</template>
<script>
import { myTitle, myDescripion } from "./constants";
export default {
name: "App",
created() {
this.$options.myTitle = myTitle;
this.$options.myDescripion = myDescripion;
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
padding: 24px;
}
</style>
Code language: HTML, XML (xml)
//constants.js
export const myTitle = "Night programmer";
export const myDescripion = "Hello from nightprogrammer.com!";
Code language: JavaScript (javascript)
The constants imported above will stay non-reactive and will stay the same during lifecycle of the component.
You can find a working demo of the above code below: