How to use plugins in DayJs with Vue using Vue DayJS

If you are looking for installation instructions, you might be able to work it out from this blog post but I have written an installation guide which will get you off the ground.

This guide contains a more advanced setup of Vue DayJS using a plugin setup.

Setup

You will need

If you are missing any node modules listed above, use your favourite package manager to install them 
npm install vue-dayjs
npm install dayjs

Note: If you do not want to use DayJS plugins, you do not need to install DayJS as well and you would probably be better off reading the installation guide I have created

File structure


Next create a file in the plugins directory (create one if you don't have one) where your app.js file is located called vue-dayjs.js (in reality you can name it whatever you like).

Your directory and file structure should look something like this

js/components/...
js/plugins/vue-dayjs.js
js/app.js
js/bootstrap.js


Vue Plugin

Next populate the file with the following


Now you have your base plugin file, we need to tell our app that it exists

In app.js we can now Import our file and add it to the app declaration

import DayJs from "./plugins/vue-dayjs";

const app = new Vue({
    el: '#app',
    DayJs
});


So that's how we can build a plugin file to set up Vue DayJS. Our aim here though is to include DayJS plugins.


DayJS Plugin

Go back into the vue-dayjs.js file and import the plugin or plugins you would like to add to DayJS such as the relative time plugin (shown below) which shows a user friendly one day ago or in ten minutes human readable output.

import relativeTime from "dayjs/plugin/relativeTime";

 After your use statement add the following:

Vue.prototype.$dayjs.extend(relativeTime);

This has now enabled the plugin for the entire Vue project. Your vue-dayjs.js file should look like something like this


Usage

The plugin I have extended above could be used in the following context on a Vue component

$dayjs().to($dayjs('2021-10-06 20:12:39'))



Reference

I have listed the all the plugins supplied with the DayJS package (version 1.10.7) for convenience

  • isYesterday.js
  • arraySupport.js
  • toArray.js
  • weekday.js
  • toObject.js
  • advancedFormat.js
  • isLeapYear.js
  • isoWeek.js
  • isToday.js
  • isBetween.js
  • buddhistEra.js
  • quarterOfYear.js
  • isSameOrBefore.js
  • devHelper.js
  • preParsePostFormat.js
  • updateLocale.js
  • timezone.js
  • duration.js
  • relativeTime.js
  • isTomorrow.js
  • localizedFormat.js
  • localeData.js
  • customParseFormat.js
  • objectSupport.js
  • isSameOrAfter.js
  • dayOfYear.js
  • pluralGetSet.js
  • isMoment.js
  • badMutable.js
  • isoWeeksInYear.js
  • calendar.js
  • minMax.js
  • weekOfYear.js
  • utc.js
  • weekYear.js

Comments