Calendar event scheduling in Vue

Introduction

Today, we’ll be creating a realtime event scheduling application. Using our application, users can easily schedule calendar events and receive realtime updates for new calendar events. We’ll be using Pusher’s pub/sub pattern to get realtime updates and Vue.js for creating the user interface.

Prerequisites

To follow this tutorial a basic understanding of Vue and Node.js is required. Please ensure that you have at least Node version 6>= installed before you begin.

We’ll be using these tools to build our application:

Here’s a demo of the final product:

vuejs-calendar-demo

Initializing the application and installing project dependencies

To get started, we will use the vue-cli to bootstrap our application. First, we’ll install the CLI by running npm install -g @vue/cli in a terminal.

To create a Vuejs project using the CLI, we’ll run the following command:

    vue create vue-eventapp

After running this command, you will be asked by the CLI to pick a preset. Please select the default preset.

Note: the @vue/cli 3.0 is still in beta and should not be used in production.

Next, run the following commands in the root folder of the project to install dependencies.

1// install depencies required to build the server
2    npm install express body-parser dotenv pusher
3    
4    // front-end dependencies
5    npm install pusher-js vue-fullcalendar@latest date-fns vuejs-datepicker

Start the app dev server by running npm run serve in a terminal in the root folder of your project.

A browser tab should open on http://localhost:8080. The screenshot below should be similar to what you see in your browser:

vuejs-default-page

Building the server

We’ll build our server using Express. Express is a fast, unopinionated, minimalist web framework for Node.js.

Create a file called server.js in the root of the project and update it with the code snippet below

1// server.js
2    
3    require('dotenv').config();
4    const express = require('express');
5    const bodyParser = require('body-parser');
6    const Pusher = require('pusher');
7    
8    const app = express();
9    const port = process.env.PORT || 4000;
10    const pusher = new Pusher({
11      appId: process.env.PUSHER_APP_ID,
12      key: process.env.PUSHER_KEY,
13      secret: process.env.PUSHER_SECRET,
14      cluster: process.env.PUSHER_CLUSTER,
15    });
16    
17    app.use(bodyParser.json());
18    app.use(bodyParser.urlencoded({extended: false}));
19    app.use((req, res, next) => {
20      res.header('Access-Control-Allow-Origin', '*');
21      res.header(
22        'Access-Control-Allow-Headers',
23        'Origin, X-Requested-With, Content-Type, Accept'
24      );
25      next();
26    });
27    
28    app.listen(port, () => {
29      console.log(`Server started on port ${port}`);
30    });

The calls to our endpoint will be coming in from a different origin. Therefore, we need to make sure we include the CORS headers (Access-Control-Allow-Origin). If you are unfamiliar with the concept of CORS headers, you can find more information here.

Create a Pusher account and a new Pusher Channels app if you haven’t done so yet and get your appId, key and secret.

Create a file in the root folder of the project and name it .env. Copy the following snippet into the .env file and ensure to replace the placeholder values with your Pusher credentials.

1// .env
2    
3    // Replace the placeholder values with your actual pusher credentials
4    PUSHER_APP_ID=PUSHER_APP_ID
5    PUSHER_KEY=PUSHER_KEY
6    PUSHER_SECRET=PUSHER_SECRET
7    PUSHER_CLUSTER=PUSHER_CLUSTER

We’ll make use of the dotenv library to load the variables contained in the .env file into the Node environment. The dotenv library should be initialized as early as possible in the application.

Draw route

Let’s create a post route named schedule, our application will send requests to this route when a user attempts to schedule events.

1// server.js
2    require('dotenv').config();
3    ...
4    
5    app.use((req, res, next) => {
6      res.header('Access-Control-Allow-Origin', '*');
7      ...
8    });
9    
10    app.post('/schedule', (req, res) => {
11      const {body} = req;
12      const data = {
13        ...body,
14      };
15      
16      pusher.trigger('schedule', 'new-event', data);
17      res.json(data);
18    });
19    
20    
21     ...
  • The request body will be sent as the data for the triggered Pusher event. The same object will be sent as a response to the user.
  • The trigger is achieved using the trigger method which takes the trigger identifier(schedule), an event name (new-event), and a payload.

Start the server by running node server in a terminal in the root folder of your project.

Calendar component

We’ll be creating a component(Calendar), this component will display our calendar with the events scheduled by a user.

Create a file called Calendar.vue in the src/components folder of your project. Open the file and copy the code below into it:

1// src/components/Calendar.vue
2    
3    <template>
4      <full-calendar :events="events" />
5    </template>
6    
7    <script>
8    import FullCalendar from 'vue-fullcalendar';
9    export default {
10      name: 'Calendar',
11      props: ['events'],
12      components: {
13        FullCalendar
14      }
15    }
16    </script>
17    
18    <style>
19    .red {
20      background: rgb(235, 77, 77) !important;
21      color: whitesmoke !important;
22    }
23    .blue {
24      background: rgb(59, 59, 163) !important;
25      color: whitesmoke !important;
26    }
27    .orange {
28      background: orange !important;
29      color: white !important;
30    }
31    .green {
32      background: rgb(49, 155, 49) !important;
33      color: white !important;
34    }
35    .blue,
36    .orange,
37    .red,
38    .green {
39      font-size: 13px;
40      font-weight: 500;
41      text-transform: capitalize;
42    }
43    .event-item {
44      padding: 2px 0 2px 4px !important;
45    }
46    </style>

Our component will make use of the Vue-fullcalendar library. The library provides a full-calendar component. Our component will receive an events prop, a list of events to be bound to the full-calendar component.

Also, we’ve added a few styles to the style section of the component. These styles will help theme the events that will be bound to the calendar. Later in the tutorial, we’ll make use of these styles.

Event form component

Now that the we’ve set up the calendar component, let’s create an EventForm component that will be used for scheduling new events.

Create a file EventForm.vue in the src/components folder. Copy the following into the file. We’ll break it down into three snippets, the template snippet, followed by the script and finally the style snippet.

Template

The template will hold the form element that will handle creation of new events.

1// /src/components/EventForm.vue
2    
3    <template>
4      <form @submit.prevent="handleSubmit">
5        <div class="input-holder">
6          <input type="text" placeholder="Event title" v-model="event.title"/>
7        </div>
8        <div class="input-holder">
9          <date-picker :placeholder="'Start date'" v-model="event.start" /> 
10        </div>
11        <div class="input-holder">
12          <date-picker :placeholder="'End date'" v-model="event.end"/> 
13        </div>
14        <div class="input-holder">
15          <textarea placeholder="Event description" rows="4" v-model="event.data.description" ></textarea>
16        </div>
17        <div class="input-holder">
18          <color-picker @colorPicked="selectColor" :color="event.cssClass" />
19        </div>
20        <div class="input-holder">
21          <button type="submit">Schedule</button>
22        </div>
23      </form>
24    </template>

In the template, we made use of the date-picker component, Vuejs-datepicker. This component will handle start and stop date selection for our events. Also, we’ll be able to theme our events using a color-picker. We haven’t gone about creating the color-picker component but that’s coming soon.

Script

We’ll handle all the functionality of our component in the script section. Update the EventForm.vue file to include the script section.

1// src/components/EventForm.vue
2    <template>
3      ...
4    </template>
5    
6    <script>
7    import DatePicker from 'vuejs-datepicker';
8    import format from 'date-fns/format';
9    import ColorPicker from './ColorPicker';
10    
11    export default {
12      name: 'EventForm',
13      data(){
14        return {
15          event: {
16            title: '',
17            start: '',
18            end: '',
19            cssClass: '',
20            data: {
21              description: ''
22            }
23          }
24        }
25      },
26      methods: {
27        async handleSubmit(){
28          const start = format(this.event.start, 'YYYY-MM-DD');
29          const end = format(this.event.end, 'YYYY-MM-DD');
30          const event = {
31            ...this.event,
32            start,
33            end
34          }
35          const req = await fetch('http://localhost:4000/schedule', {
36            method: 'POST',
37            body: JSON.stringify(event),
38            headers: {
39              'content-type': 'application/json'
40            }
41          });
42          const res = await req.json();
43          this.resetValues();
44        },
45        selectColor(color){
46          this.event = {
47            ...this.event,
48            cssClass: color
49          }
50        },
51        resetValues(){
52          this.event = {
53            title: '',
54            start: '',
55            end: '',
56            cssClass: '',
57            data: {
58              description: ''
59            }
60          }
61        }
62      },
63      components: {
64        DatePicker,
65        ColorPicker
66      }
67    }
68    </script>

In our scripts section, we have one data property, event, this will hold all the data needed to schedule an event. The methods property has three methods. The handleSubmit method uses the date-fns library to format the start and end dates and then sends the data to the server to schedule an event. When a response is returned, the data in the response is emitted to the parent component. The resetvalues method resets the values to their initial state.

The selectColor method will be bound to the colorPicked event emitted by the color-picker component. This method is triggered whenever a color is selected.

Styles

Update the component with the following styles:

1// src/components/EventForm.vue
2    <template>
3      ...
4    </template>
5    
6    <script>
7      ...
8    </script>
9    
10    <style>
11      form {
12      display: flex;
13      flex-direction: column;
14      margin-left: 30px;
15    }
16    .input-holder {
17      margin: 10px 0;
18      display: flex;
19      justify-content: flex-start;
20    }
21    .vdp-datepicker {
22      width: 100%;
23    }
24    .vdp-datepicker > div > input {
25      width: 77%;
26    }
27    .input-holder > button {
28      justify-self: center;
29      padding: 12px 25px;
30      border-radius: 0;
31      text-transform: uppercase;
32      font-weight: 600;
33      background: orangered;
34      color: white;
35      border: none;
36      font-size: 14px;
37      letter-spacing: -0.1px;
38      cursor: pointer;
39    }
40    input,
41    textarea {
42      padding: 12px 15px;
43      border: 2px solid rgba(0, 0, 0, 0.2);
44      border-radius: 0;
45      width: 70%;
46      opacity: 0.8;
47      font-size: 15px;
48      font-weight: normal;
49    }
50    input:focus,
51    textarea:focus,
52    button:focus {
53      border: 2px solid orangered;
54      outline: none;
55      box-shadow: 0 2px 3px 1px rgba(0, 0, 0, 0.2);
56    }
57    </style>

Next, let’s create the color-picker component.

Color picker component

The color component will help us theme our event by letting us select a color that suits the event. Create a file named ColorPicker.vue in the src/components/ directory and update it with the code below:

1// src/components/ColorPicker.vue
2    
3    <template>
4      <div class="picker-main"> 
5        <h4 class="header">Select event theme</h4>
6        <div class="color-picker">
7          <div class="color" v-for="(theme, index) in colors" :key="index" @click="selectColor(theme)" :class="{selected: color === theme, [theme]: theme}"></div>
8        </div>
9      </div>
10    </template>
11    
12    <script>
13    export default {
14      name: 'ColorPicker',
15      props: ['color'],
16      data(){
17        return {
18          colors: ['red', 'green', 'blue', 'orange']
19        }
20      },
21      methods: {
22        selectColor(color){
23          this.$emit('colorPicked', color);
24        }
25      }
26    }
27    </script>
28    <style scoped>
29    .picker-main {
30      width: 55%;
31    }
32    .header {
33      font-size: 14px;
34      text-transform: uppercase;
35      color: orangered;
36      letter-spacing: 0.5px;
37      margin: 0 0 6px;
38      text-align: left;
39    }
40    .color-picker {
41      display: flex;
42      justify-content: space-around;
43    }
44    .color-picker > .color {
45      width: 40px;
46      height: 40px;
47      border-radius: 50%;
48      border: 1.5px solid whitesmoke;
49      cursor: pointer;
50    }
51    .color.selected{
52      box-shadow: 0 2px 3px 1px rgba(0, 0, 0, 0.2);
53      border: 3px solid rgba(0, 0, 0, 0.4);
54    }
55    .color.red {
56      background: rgb(235, 77, 77);
57    }
58    .color.blue {
59      background: rgb(59, 59, 163);
60    }
61    .color.orange {
62      background: orange;
63    }
64    .color.green {
65      background: rgb(49, 155, 49);
66    }
67    </style>

In the template section, we loop through an array of colors, creating a clickable element that emits a color when clicked. The component takes a prop color from the parent component.

App component

Now that we’ve built out the components to be used for our application, let’s render them in the App component to create a usable application. Open the App.vue file and update it to look like the snippet below:

1// src/App.vue
2    
3    <template>
4      <div id="app">
5        <div class="main">
6          <div class="calendar-holder">
7            <calendar :events="events" />
8          </div>
9          <div class="form-holder">
10            <h3>Schedule an event</h3>
11            <event-form />
12          </div>
13        </div>
14      </div>
15    </template>
16    <script>
17    import Calendar from './components/Calendar.vue'
18    import EventForm from './components/EventForm.vue'
19    import Pusher from 'pusher-js';
20    export default {
21      name: 'app',
22      components: {
23        Calendar,
24        EventForm
25      },
26      data(){
27        return {
28          events: [{
29            title     :  'event1',
30            start     : '2018-07-09',
31            cssClass  : 'blue',
32            YOUR_DATA : {}
33          },
34          {
35            title     : 'event2',
36            start     : '2018-07-10',
37            end       : '2018-07-13',
38            cssClass  : ['orange']
39          }] 
40        }
41      }
42    }
43    </script>
44    <style>
45    #app {
46      font-family: 'Avenir', Helvetica, Arial, sans-serif;
47      -webkit-font-smoothing: antialiased;
48      -moz-osx-font-smoothing: grayscale;
49      text-align: center;
50      color: #2c3e50;
51      margin-top: 60px;
52    }
53    .main {
54      display: flex;
55      align-items: center;
56    }
57    .calendar-holder {
58      width: 65%;
59    }
60    .form-holder {
61      width: 35%;
62    }
63    .form-holder > h3 {
64      color: orangered;
65      text-transform: uppercase;
66      font-size: 16px;
67      text-align: left;
68      margin-left: 30px;
69      margin-bottom: 10px;
70    }
71    </style>

We’ve populated the data property with a list of events. There is a method handleNewEvent, this method is bound to the event-form component. It appends the new event emitted from the event-form component to the list of events.

You can now check out the current look of the application by visiting http://localhost:8080. Make sure both the vue dev server (yarn serve) and the server (node server) are running in separate terminals in the root folder of your project.

vuejs-calendar-partial

Introducing Pusher and realtime updates

Our application will update in realtime whenever there’s a new event added. We’ll be using Pusher’s pub/sub pattern to enable this functionality in our application.

We’ll update the App component to include the created lifecycle. It’s in this lifecycle we’ll initialise Pusher and listen for new events. Open the App.vue file and update it to match the snippet below:

1// /src/App.vue
2    <template>
3      ...
4    </template>
5    <script>
6    import Calendar from './components/Calendar.vue'
7    import EventForm from './components/EventForm.vue'
8    import Pusher from 'pusher-js';
9    
10    export default {
11      name: 'app',
12      components: {
13        ...
14      },
15      data(){
16        ...  
17      },
18      created(){
19        const pusher = new Pusher('PUSHER_KEY', {
20          cluster: 'PUSHER_CLUSTER',
21          encrypted: true,
22        });
23        const channel = pusher.subscribe('schedule');
24        channel.bind('new-event', (data) => {
25          this.events = [
26            ...this.events,
27            data
28          ];
29        })
30      }
31    }
32    </script>
33    <style>
34      ...
35    </style>

Note: ensure you replace the PUSHER_KEY and PUSHER_CLUSTER placeholder strings with your actual credentials.

In the created lifecycle, we initialized Pusher, subscribed to the schedule channel and listened for the new-event event. In the callback, we appended the data returned from the event to the list of events.

Test application

Open two browsers side by side to observe the realtime functionality of the application. Events scheduled on one browser are picked up by the other browser. Here’s a screenshot of two browsers side by side using the application:

Note: Ensure both the server and the dev server are up by running npm run serve and node server on separate terminal sessions.

vuejs-calendar-demo

Conclusion

We’ve created an event scheduling application using Vue.js, using Pusher to provide realtime functionality. You can think up new ideas to extend the application. It’ll be fun to see what you come up with. The source code for this tutorial is available on GitHub here.