Open In App

Create a Chat App with Vue.js

In this article, we will explore how to build a real-time chat application using Socket.IO and Vue.js. Socket.IO is a popular library that enables real-time, bidirectional, and event-based communication between the client and the server. By integrating Socket.IO with Vue.js, we can create a seamless and interactive chat experience for users.

Prerequisites

Approach

Steps for the Vue.js project

Step 1: Run the command to create a Vue.js app

npm init vue@latest

Step 2: Give name to your project and go to that project

cd my-chat-app

Step 3: Install the required dependencies:

Install the Socket.IO library for real-time communication

npm install socket.io
npm install socket.io-client

update dependencies looks like:

"dependencies": {
        "socket.io": "^4.7.5",
        "socket.io-client": "^4.7.5",
        "vue": "^3.4.21"
      },

Project Structure:

project structure

Step 4: Set up the server-side code:

Create a new directory called server in the project root. and navigate to the server directory:

mkdir server
cd server

Project structure:

Screenshot-2024-04-28-225416

Step 5: Initialize a new Node.js project and install the required dependencies:

npm init -y
npm install socket.io http

Updated dependencies looks like:

"dependencies": {
        "http": "^0.0.1-security",
        "socket.io": "^4.7.5"
      }

Step 6: Create a new file called index.js and add the following code:

//server/index.js
const http = require('http');
const fs = require('fs');
const socketIo = require('socket.io');

const port = 5000;
const server = http.createServer((req, res) => {
  if (req.url === '/') {
    fs.readFile(__dirname + '/index.html', (err, data) => {
      if (err) {
        res.writeHead(500);
        res.end('Error loading index.html');
      } else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(data);
      }
    });
  }
});

const io = socketIo(server, {
  cors: {
// Replace with your client-side URL origin: 'http://localhost:5173', methods: ['GET', 'POST'] } }); io.on('connection', (socket) => { console.log('A user connected'); socket.on('send message', (chat) => { io.emit('send message', chat); }); }); server.listen(port, () => { console.log(`Server is listening at the port: ${port}`); });

Step 7: Integrate the Vue.js components. add these codes into respective files.

/* style.css */

body {
    background-color: #464e46;
    margin: 0;
    padding: 0;
    font-family: Arial, sans-serif;
}

.container {
    max-width: 400px;
    margin: 80px auto;
    padding: 20px;
    background-color: white;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.logo {
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #008000;
}

.form {
display: flex;
flex-direction: column;
align-items: center;
}

.input {
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;
    margin-bottom: 10px;
    width: 100%;
}

.button {
    background-color: #008000;
    color: white;
    border: none;
    border-radius: 5px;
    padding: 10px;
    width: 100%;
    cursor: pointer;
}

.messageArea {
    margin-top: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;
    height: 200px;
    overflow-y: scroll;
}

.message {
    margin-bottom: 5px;
}

.username {
    font-weight: bold;
    color: #005180;
}
//ChatForm.vue

<template>
  <form class="form" @submit.prevent="sendMessage">
    <input class="input" type="text"
            placeholder="Name" 
            v-model="username" />
    <input class="input" type="text" 
           placeholder="Message"
           v-model="message" />
    <button class="button">Send Message</button>
  </form>
</template>

<script>
import { io } from 'socket.io-client';

export default {
  data() {
    return {
      username: '',
      message: '',
      socket: io('http://localhost:5000'),
    };
  },
  methods: {
    sendMessage() {
      if (this.message && this.username) {
        this.socket.emit('send message',
        { username: this.username,
        content: this.message });
        this.message = '';
      }
    },
  },
};
</script>
//ChatMessage.vue

<template>
  <div class="messageArea">
    <p class="message" v-for="message in messages"
                       :key="message.id">
      <span class="username">{{ message.username }}:</span>
      <span class="content">{{ message.content }}</span>
    </p>
  </div>
</template>

<script>
import { io } from 'socket.io-client';

export default {
  data() {
    return {
      messages: [],
      socket: io('http://localhost:5000'),
    };
  },
  mounted() {
    this.socket.on('send message', (message) => {
      this.messages.push(message);
    });
  },
};
</script>
/App.vue

<template>
  <div class="container">
    <h1 class="logo">GeeksforGeeks ChatApp</h1>
    <ChatForm />
    <ChatMessage />
  </div>
</template>

<script>
import ChatForm from './components/ChatForm.vue';
import ChatMessage from './components/ChatMessage.vue';

export default {
  components: {
    ChatForm,
    ChatMessage,
  },
};
</script>

<style>
@import './style.css';
</style>

Step 8: Start the development server:

In the project root directory, run the following command to start the Vue.js development server

npm run dev

Step 9: In a separate terminal, navigate to the server directory and start the server

node index.js

The application should now be running, and you can access it at http://localhost:3000. The server-side code is running at http://localhost:5000 and handling the real-time communication using Socket.IO.

Output:

chat

Article Tags :