July 22, 2020

Create a Chat App with Vue.js

Olususi Oluyemi

Introduction

A chat feature, containing groups or just one-on-one conversations, is arguably one of the best features that help to promote user engagement for a web or mobile application as it helps your users to easily stay in touch. Building such a feature comes with its challenges as it requires some level of expertise and can be time-consuming. Fortunately, this is one of the reasons why CometChat infrastructure was set up.


In this tutorial, I will show you how to easily craft a group chat application built in Vue.js. To facilitate the implementation of this application, we will use a collection of custom UI Components designed by the CometChat team. This UI kit built in Vue.js, will help developers build chat applications swiftly with minimal changes required, exhibiting features similar to what we have below:



This shows three different users ( participants ) with usernames of superhero1, superhero2 and superhero3. The next image shows the conversation between them.



The complete source code for this tutorial can be found here on GitHub. You can download or clone the repository if you want to dive into the code. Ensure to return to this tutorial for a proper step-by-step guide on how to set it up.


Creating a CometChat Account

Before we begin, you will first require a CometChat account. Steps to do this:

Enter the desired name for your application, select a region, technology, and a use case. Once you are done, click on the Add App button to complete the process.


This will automatically spin up a new application for you on CometChat and take you to the quick start guide. CometChat Quick Start guide does a wonderful job in explaining the steps in detail.  



Copy your APP_ID, API_KEY and APP_REGION details. Keep this information safe as it will be required later in this tutorial.


Getting started

With the CometChat account created and out of the way, we will proceed to create a new Vue.js application by using Vue CLI. Run the following command to install Vue CLI:


{% c-line %}npm install -g @vue-cli{% c-line-end %}

Once its done, create a new Vue.js project with:


{% c-line %}vue create vue-chat-app{% c-line-end %}


The preceding command will start the creation of our Vue.js project. You will be prompted with an option to chose a “default” preset or “manually select features”. Choose the latter by pressing Enter on your keyboard. Next, a list of feature options will be displayed, use the arrow key to move down and use the spacebar to select Babel, Router, Linter / Formatter and hit Enter once you are done. After that, type y to use history mode for router and select ESLint with error prevention only. Finally select Lint on save for additional lint features and proceed to choose an option to save your configuration in a dedicated config file for future projects.



Install CometChat

Before we run the just installed Vue.js project, let us quickly install the CometChat package for our application. With this in place, we can easily connect with CometChat to access some of its awesome features. To proceed, move into the newly created project and run the following command:


{% c-line %}cd vue-chat-app{% c-line-end %}

{% c-line %} npm install @cometchat-pro/chat --save{% c-line-end %}


After installing CometChat successfully, it can then be referenced from our project as:


{% c-line %}import { CometChat } from '@cometchat-pro/chat'{% c-line-end %}


Run the application with npm run serve and view the default homepage on http://localhost:8080.




Initialize CometChat

To be able to call and use methods from CometChat, the SDK needs to be initialize within our application using the APP_ID of the app created on CometChat earlier. To do so, create a .env file within the root of your project and paste the following content in it:


{% c-block language="javascript" %}
VUE_APP_COMMETCHAT_API_KEY=YOUR_API_KEY        
VUE_APP_COMMETCHAT_APP_ID=YOUR_APP_ID
VUE_APP_COMMETCHAT_GUID=supergroup
VUE_APP_COMMETCHAT_REGION=YOUR_APP_REGION
{% c-block-end %}


Be sure to replace the YOUR_API_KEY, YOUR_APP_ID, YOUR_APP_REGION with the appropriate content from your dashboard. Please note you can use a different GUID other than the one that I have stated above.


Next, open src/main.js and initialize CometChat within it by replacing its content with the following:


{% c-block language="javascript" %}
import
Vue from "vue";
import
App from "./App.vue";
import
router from "./router";
import
{ CometChat } from "@cometchat-pro/chat";
Vue.config.productionTip = false;
const { VUE_APP_COMMETCHAT_APP_ID, VUE_APP_COMMETCHAT_REGION } = process.env;
let cometChatAppSetting = new CometChat.AppSettingsBuilder()
 .subscribePresenceForAllUsers()
 .setRegion(VUE_APP_COMMETCHAT_REGION)
 .build();
CometChat.init
(VUE_APP_COMMETCHAT_APP_ID, cometChatAppSetting).then(
 () => {
   console.log("Initialization completed successfully");
 new Vue({
     router,
     render: (h) => h(App),
   }).$mount("#app");
 },
 (error) => {
   console.log("Initialization failed with error:", error);
 }
);
{% c-block-end %}


What we have done in the file above is to call the init() method from CometChat with the appropriate App ID and Region.

Creating views and components

Here, we will start by creating the view files required by our application. This chat application will need to authenticate users and once the authentication process is successful, the user will be redirected to a chat page where they can interact with other participants. To avoid spending a lot of time and effort crafting an appealing user interface for our chat view, we will leverage the UI kit created by CometChat team here on GitHub to easily get started.


Cloning the UI kit

To integrate, clone the Vue chat UI kit into your application using the following command:


git clone https://github.com/cometchat-pro/vue-chat-ui-kit.git


Now open the UI Kit source code with a code editor or any file explorer and copy the cometchat-components folder. Then create a new folder named lib within the src folder of your project and paste the cometchat-components in it. With this in place, you can then easily reference and make use of some of the custom UI component to easily set up views for your application.



Creating the Authentication Component

It is required that every user gets authenticated to start a chat using CometChat. To create a view and necessary logic for that, proceed to rename the About.vue file found in src/views folder to Auth.vue and replace its content with the following:


{% c-block language="html" %}
<template>
 <div class="light">
   <div class="pageWrapper" v-if="!loader">
     <div class="input-form">
       <form v-on:submit.prevent="login">
         <h3>Hello!</h3>
         <p>
           Welcome to our little Vue demo powered by CometChat. Login with the
           username "superhero1" or "superhero2" and test the chat out. To
           create your own user, see
           <a
             href="https://prodocs.cometchat.com/reference#createuser"
           >our documentation</a>
         </p>
         <input
           id="username"
           name="username"
           v-model="uid"
           type="text"
           placeholder="Enter your UID here"
           class="formInput"
         />
         <button class="pageButton" type="submit">
           Login &nbsp;&nbsp;
           <span v-if="loader" class="fa fa-spin fa-spinner"></span>
         </button>
       </form>
     </div>
   </div>
   <Loader v-else-if="loader" />
 </div>
</template>
<script>
import
{ CometChat } from "@cometchat-pro/chat";
import
Loader from "../lib/cometchat-components/components/Loader";
export
default {
 components: {
   Loader
 },
 data() {
   return {
     uid: "",
     loader: false
   };
 },
 methods: {
   login() {
     let apiKey = process.env.VUE_APP_COMMETCHAT_API_KEY;
     this.loader = true;
     console.log(this.uid, apiKey);
     CometChat.login(this.uid, apiKey).then(
       user => {
         this.loader = false;
         console.log("Login successfully:", { user });
         this.$router.push({
           name: "chat"
         });
       },
       error => {
         this.loader = false;
         console.log(error);
         alert(
           "Whops. Something went wrong. This commonly happens when you enter a username that doesn't exist. Check the console for more information"
         );
         console.log("Login failed with error:", error.code);
       }
     );
   }
 }
};
</script>
{% c-block-end %}



From the <template></template> section within the code snippet above, we created a form with an input field to receive the username, also known as UID, of a particular user for authentication purposes. Next, we utilized the <Loader /> component from the downloaded UI kit and lastly, we set up a condition to render the <Loader /> once we start submitting the form.


And within the <script></script> section, we created a custom login() method and within it, we passed the users’ unique identifier to a login() method from CometChat() class to get the user authenticated on CometChat as a valid user. Once logged in, the user will be redirect to a chat page that we will create in the next section. The image below depicts what the login page will look like:




To add some custom stylesheet, add the following content to the  <style></style> section of the Auth.vue file:


{% c-block language="html" %}
<style>
.pageWrapper {
 padding-top: 50px;
 text-align: center;
 display: flex;
}
.input-form {
 margin: 0 auto;
 width: 400px;
}
.formInput {
 border: 2px solid #aaa;
 width: 100%;
 padding: 10px;
 font-weight: 550;
 color: #555;
 margin-top: 40px;
 margin-bottom: 30px;
}
p {
 margin: auto;
 padding: 10px;
}
.pageButton {
 color: white;
 padding: 10px;
 text-align: center;
 background: #333;
 width: 100%;
}
.pageButton:hover {
 cursor: pointer;
 color: white;
 background: #333333;
}
</style>
{% c-block-end %}


The complete src/views/Auth.vue file can be found here, if you missed a step.


Creating the chat component

Begin by renaming the Home.vue file within src/views folder to Chat.vue. Once you are done, replace its content with:


{% c-block language="html" %}
<template
 <div>
   <div class="page-wrapper">
     <div
       class="page-int-wrapper"
       id="pageWrapper"
       :class="{
         'left-open': leftOpen,
         'center-open': centerOpen,
         'right-open': rightOpen,
       }"
     >
       <div class="ccl-left-panel">
         <GroupList />
       </div>
       <MessageContainer :currentUser="currentUser" />
       <RightSidebar />
     </div>
   </div>
 </div>
</template>
{% c-block-end %}



Here, we created a structure that brings together different UI components to represent and build a chat view of our application. Each of the components referenced here is from the UI kit downloaded earlier.


To import these components and the appropriate logic for the application, use the following content for the <script></script> section within the file:


{% c-block language="javascript" %}
<script>
import
{ CometChat } from "@cometchat-pro/chat";
import
GroupList from "../lib/cometchat-components/components/GroupList";
import
MessageContainer from "../lib/cometchat-components/components/MessageContainer";
import
RightSidebar from "../lib/cometchat-components/components/RightSidebar";
export
default {
 components: {
   GroupList,
   MessageContainer,
   RightSidebar
 },
 data() {
   return {
     currentUser: null,
     leftOpen: true,
     centerOpen: false,
     rightOpen: false
   };
 },
 created() {
   CometChat.getLoggedinUser().then(
     user => {
       console.log("we are here", user);
       this.currentUser = user;
       if (!user) {
         this.$router.push({
           name: "home"
         });
       }
     },
     error => {
       console.log(error);
       this.$router.push({
         name: "home"
       });
     }
   );
 },
 mounted() {
   this.$root.$on("selectedUser", data => {
     console.log(data);
     const el = document.getElementById("pageWrapper");
     if (el.classList.contains("left-open")) {
       el.classList.add("center-open");
       el.classList.remove("left-open");
     }
   });
 }
};
</script>
{% c-block-end %}


First, we imported CometChat SDK and three different components from the cometchat-components folder:

  • GroupList: This component will list the number of groups that an authenticated CometChat app user belongs to. With that, a user can easily select a particular chat group he or she will like to participate in.
  • MessageContainer: This is a very important component for the chat view. It holds the logic to render different message types (Video, Audio, Media, Text) sent to a group or participants during a chat. It has a structure that houses the header of a chat view, the body, that is, the message sent in a group and finally the form with an input fields where messages for a group chat are composed.
  • RightSidebar: This component house the sidebar on the right hand side of the chat view. It is hidden by default and for the sake of this tutorial, we won’t focus on it.


Next, we used the getLoggedinUser() method from the CometChat() class to retrieve the details of the currently logged in user.


Adding a logout button

For users to be able to log out we will include a button on the GroupList.vue file. To do that, open src/lib/cometchat-components/components/GroupList.vue file and include a button within the <template></template>


{% c-block language="javascript" %}
<template>
 <div>
   ...
   <button
     style="text-align: center; cursor: pointer;"
     class="pageButton"
     v-on:click="logout()"
   >Logout</button>
 </div>
</template>
{% c-block-end %}


Next, add the logout() method within the <script></script> section as shown here:


{% c-block language="javascript" %}
<script>
 ...
export
default {
 ...
 methods: {
   ...
   logout() {
     this.loader = true;
     CometChat.logout().then(() => {
       this.loader = false;
       this.$router.push({
         name: "home"
       });
     });
   }
 },
 ...
};
</script>
{% c-block-end %}


Once the Logout button is clicked, the user will be logged out on CometChat and then be redirected back to the login page.


Updating the router file

Open the router file in src/router/index.js file and replace its content with the following:


{% c-block language="javascript" %}
import
Vue from "vue";
import
VueRouter from "vue-router";
import
Auth from "../views/Auth.vue";
import
Chat from "../views/Chat.vue";
Vue.use
(VueRouter);
const routes = [
 {
   path
: "/",
   name
: "home",
   redirect
: "login",
 },
 {
   path
: "/login",
   name
: "login",
   component
: Auth,
 },
 {
   path
: "/chat",
   name
: "chat",
   component
: Chat,
 },
];
const router = new VueRouter({
 mode
: "history",
 base
: process.env.BASE_URL,
 routes,
});
export
default router;
{% c-block-end %}


Here, we have created endpoints and referenced all the views created for our chat application.



Updating the AppComponent

Finally, open the src/App.vue component and replace its content with the following:


{% c-block language="html" %}
<template>
 <div id="app">
   <router-view />
 </div>
</template>
<style>
@import "./lib/cometchat-components/assets/css/style.css";
</style>
{% c-block-end %}



Test the application

Restart the application by typing CTRL + C from the terminal while you are within the project and then use npm run serve to start it again. Navigate to http://localhost:8080 and open different browser similar to what we have below:




Log in with the following sample usernames superhero1, superhero2 and superhero3 and start chatting:




Conclusion

CometChat already created an existing structure that can easily help facilitate the implementation of chat feature for a new or an existing Vue.js application without much hassle. As seen from this tutorial, we were able to build a Vue.js application from scratch and leverage on the custom UI kit made available by CometChat to easily implement the logics and proper user interface for our application. The Vue UI Chat kit does not only contain boilerplate for a group chat, it also comes with the appropriate logics to help, if you are willing to extend the functionalities of your chat application by including image upload, text and video chat.


The complete source code for this tutorial can be found here on GitHub. Please feel free to explore it and add more features. Looking forward to seeing what you will build. Lastly, don’t hesitate to check out the official documentation of CometChat Pro for some other features and more details on all its products. Happy coding!