Sometimes, we want to use moment.js with Vue.js to make date calculations easier.
In this article, we’ll look at how to use moment.js with Vue.js to make date calculations easier.
Use Moment.js with Vue.js
We can use moment.js in our components by calling it in methods.
For instance, we can write:
<template>
<div id="app">
{{ moment().format("MMMM Do YYYY, h:mm:ss a") }}
</div>
</template>
<script>
import moment from "moment";
export default {
name: "App",
methods: {
moment() {
return moment();
},
},
};
</script>
to add the moment
method that returns the return result of the moment
function.
Then we call it in our template to show today’s date.
We can also add a filter to our Vue app that uses the moment
function.
For instance, we can write:
<template>
<div id="app">
<span>{{ new Date() | moment }}</span>
</div>
</template>
<script>
import moment from "moment";
export default {
name: "App",
filters: {
moment(date) {
return moment(date).format("MMMM Do YYYY, h:mm:ss a");
},
},
};
</script>
to add the moment
filter that takes the date
and returns a date string formatted in the given format.
Conclusion
We can use moment.js in our components by calling it in methods.