We'll show you how to use the TalkJS chat API to build a chat into your Vue app. By using an example application we will look at how we can add a chat to an existing Vue.js app in a matter of minutes. You can also check out the Vue getting started guide.

Application Overview

Sign In Page

A Great University runs our fictitious application. It allows their students to take live lectures, but it lacks the ability to chat with professors and amongst themselves in real-time. Currently, the web app consists of a landing page where the student's log in with their university credentials (Name, Email and Password). Once they log in, they are taken to the live lecture. For simplicity's sake, we have
assumed that there's only one live lecture, which in our case is just a YouTube video, and that all the students are already authenticated. The currentUser object we will use throughout the tutorial will contain data that we've received from the backend after the login and auth process.


Our focus is on integrating a chat into an existing Vue app and not creating a whole app from scratch.

Adding TalkJS to our application

We begin by adding TalkJS to our application. This can be done in one of two ways.

If you use the Node Package Manager, run the following command. It will save it as a dependency in the packages.json:

npm install talkjs --save

If you use Yarn Package Manager, run the following command:

yarn add talkjs

Now that you have TalkJS installed, you need to signup on their website and register your application. This is a very simple process, at the end of which you will receive your APPID. Keep hold of this, it's very important, and we will use this later.

Creating the chatbox Vue component

Every Vue component is housed in its own .vue file. In this case, here are the steps to be followed:

  • We will create a component called MessageBox in MessageBox.vue.
  • Under the template, we create a div, as shown in the image below.
  • The div has a ref attribute set to "talkjs-container" we will use
    this to mount the actual chat box in this div later.
  • The <i> tag is only used as a placeholder until the chatbox loads. We have added some styling, but that is left to the reader's
    discretion.
<template>
    <div
        class="col-xs-4"
        id="talkjs-container"
        ref="talkjs-container"
        style="width: 90%; margin-top: 10px; height: 900px"
    >

    <i>Loading chat...</i>

    </div>
</template>

Below is a template that is added through a script tag. This will contain all the setup and logic for the TalkJS chatbox. Here the first thing we need to do is import TalkJS. To do that, add the following at the start of the script section:

import Talk from "talkjs";

Next, we export this component and name it MessageBox. This component will accept one prop of type object that contains the user's information.

It has two variables that it needs to maintain, so we add conversation and chatbox to the data function.

<script>
import Talk from "talkjs";
    export default {
        name: "MessageBox",
        data() {
            return {
                conversation: null,
                chatbox: null,
            };
        },
        props: {
            currentUser: {
                type: Object,
                required: true,
            },
        },
    }

Our chatbox will render once our MessageBox component has mounted, and as such, all chatbox logic will have to run inside the mounted lifecycle function that Vue provides. The mounted function will be defined just below our props object, and it will look something like this.

Creating the users

The Talk object we imported from TalkJS is promise-based. Hence we call the ready function and then add our logic as a call back to the .then() function. Here we create our use through Talk.User() function. It accepts a JSON object with the ID, Name, Email, photo URL of our user, and a role we set to default. For the sake of demonstration, we have also added another dummy user Sebastian in the other variable. In your application, you would add your own users using their data from your database.

mounted() {
    Talk.ready.then(() => {
        // creating our user
        var me = new Talk.User({
            id: this.currentUser.id,
            name: this.currentUser.name,
            email: this.currentUser.email,
            photoUrl: "https://randomuser.me/api/portraits/men/83.jpg\",
            role: "default",
        });

        // creating other users
        var other = new Talk.User({
            id: "654321",
            name: "Sebastian",
            email: "Sebastian@example.com",
            photoUrl: "https://randomuser.me/api/portraits/men/69.jpg",
            welcomeMessage: "Hey, how can I help?",
            role: "default",
        });

Establishing a TalkJS session

There can't be a chat if there's no chat session, hence we establish a talk session and add it to our browser's window's instance.


// establishing a new session if one doesn\'t already exists*
if (!window.talkSession) {
    window.talkSession = new Talk.Session({
        appId: "YOU_APP_ID",
        me: me,
    });
}

The APPID you found on your dashboard will be used here to establish a connection if one doesn't already exist. This connection will let us join chats and start conversations. You also specify the user trying to establish the connection by passing the current user as a theme object.

Creating a new or joining an existing conversation

Next, we join or start an existing conversation. Each conversation on TalkJS has a unique id. These ids can be stored in your database and used when joining group conversations or a conversation with someone. For our demonstration we will hard code it to 1001, all the students joining this lecture will be added to the conversation with the ID 1001.

// connecting to a new or already existing conversation
this.conversation = window.talkSession.getOrCreateConversation("1001");
this.conversation.setAttributes({ subject: "Computational Theory 101"});

// adding participants

this.conversation.setParticipant(me);
this.conversation.setParticipant(other);

The getOrCreateConversation() function will fetch the conversation if it already exists or create a new instance. Note that we are initializing the conversation variable we defined earlier, this is so we can access the conversation object later if necessary. Once the conversation has been initialized, we add its participants, and naturally, it is going to be the two users, me and others we created beforehand.

Creating an Inbox and mounting it

Like a usual conversation, we will initialize the inbox variable we defined above using the createInbox function of our talkSession. We will pass our conversation as the focus of this inbox by setting selected to our conversation.

// creating the actual inbox/chatbox
this.inbox = window.talkSession.createInbox({
    selected: this.conversation,
});

Last but not least, we will mount our inbox to the div we added a ref to in the template section. But before this, we need to ensure that the ref we are going to point to has been initialized. Which is why we will use Vue's $nextTick() function. It will ensure that the following code runs only after the required div, and ref are rendered and are ready to be addressed. In order to mount the inbox, we just call the mount function on the inbox object and pass this ref of our div, which
we set to "talkjs-container".

The Result

Image 2

With this we've successfully added a chat box to our application. This group chat supports up to 20 users in the basic plan and up to 40 in the growth plan; however, more refinements will drastically increase these limits, such as the rolling enterprise plan. The chatbox would look something like this. This is the default design, and you can change it endlessly from the TalkJS dashboard.

The GIF below demonstrates the functional design of the chatbox.

Final Gif
You’ve successfully subscribed to TalkJS
Welcome back! You’ve successfully signed in.
Great! You’ve successfully signed up.
Your link has expired
Success! Check your email for magic link to sign-in.