Sometimes, we want to use constants in Vue.js component templates.
In this article, we’ll look at how to use constants in Vue.js component templates.
Use Constants in Vue.js Component Templates
To use constants in Vue.js component templates, we can expose them to the template by putting them in the object returned by the data
method.
For instance, we can write:
<template>
<p>{{ CREATE_ACTION }}</p>
<p>{{ UPDATE_ACTION }}</p>
</template>
<script>
const CREATE_ACTION = "create";
const UPDATE_ACTION = "update";
export default {
name: "App",
data() {
return {
CREATE_ACTION,
UPDATE_ACTION,
};
},
};
</script>
to add the constants we want to use in the template with:
const CREATE_ACTION = "create";
const UPDATE_ACTION = "update";
Then we put them both in the object we return in the data
method.
Finally, we use the in the template by putting them in between their own curly braces.
Now we see:
create
update
displayed.
Conclusion
To use constants in Vue.js component templates, we can expose them to the template by putting them in the object returned by the data
method.