Home Web Front-end Vue.js How to build real-time chat and instant messaging applications using Vue?

How to build real-time chat and instant messaging applications using Vue?

Jun 27, 2023 pm 05:44 PM
vue instant messaging Live chat

In recent years, real-time chat and instant messaging have become an essential part of people's daily life and work. Whether it’s social media, team collaboration, or customer service, it all needs real-time communication to support it. Vue.js is a JavaScript framework suitable for building real-time chat and instant messaging applications. This article will introduce how to use Vue to build a real-time chat and instant messaging application.

1. Introduction to Vue and Socket.io

Vue is a popular JavaScript framework. It is a responsive framework that can help developers handle DOM operations and data binding more easily. logic. As an MVC framework, Vue performs very well in single-page applications, thanks to Vue's extremely high adaptability, efficiency, and power. Socket.io is a tool that provides real-time, two-way, event-driven communication to clients and servers based on WebSocket.

2. The combination of Vue and Socket.io

Building real-time chat and instant messaging applications requires the combination of Vue and Socket.io. In Vue, we can manage status in live chat and instant messaging applications through vuex. We can use Vuex to manage user information, session information, messages, notifications and other related data. In Socket.io, we can use it to implement real-time communication mechanism.

  1. Install Vue and Socket.io

To install Vue and Socket.io you need to enter the following command in the command line tool:

npm install --save vue
npm install --save socket.io-client
Copy after login
  1. Using Socket.io to establish a connection

Using Socket.io to establish a connection requires introducing the socket.io-client module in the client:

import io from 'socket.io-client'
const socket = io('http://localhost:3000')
Copy after login

In this example, we established a The socket named is connected to port 3000 of the local host (localhost). Next, we can use this socket in the Vue component to listen and emit events.

  1. Listening and sending events

In the Vue component, we can use the $socket variable to introduce the socket.io-client instance. As shown below:

mounted() {
  this.$socket.on('connect', () => {
    console.log('Connected to server!')
  })
}
Copy after login

In this example, we listen to a connect event immediately after the component is mounted, and when the connection is successful, we will see a message in the console.

We can also use the emit method of socket to send events. As shown below:

methods: {
  sendMessage() {
    this.$socket.emit('message', this.message)
  }
}
Copy after login

In this example, we define a sendMessage method, and we use $socket.emit to emit an event named message to the server.

3. Implementation of using Vue and Socket.io to build real-time chat and instant messaging applications

We can use Vue and Socket.io to build a real-time chat and instant messaging application.

  1. Create Vuex Store

Vuex Store is used to store user information, session information, messages and notifications. We can use the following code to create a Vuex Store:

import Vue from 'vue'
import Vuex from 'vuex'
import io from 'socket.io-client'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {
      id: null,
      name: null
    },
    rooms: [],
    activeRoomId: null,
    messages: []
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setRooms(state, rooms) {
      state.rooms = rooms
    },
    setActiveRoomId(state, roomId) {
      state.activeRoomId = roomId
    },
    addMessage(state, message) {
      state.messages.push(message)
    },
    clearMessages(state) {
      state.messages = []
    }
  },
  actions: {
    connect({ commit, dispatch }) {
      const socket = io('http://localhost:3000')

      socket.on('connect', () => {
        console.log('Connected to server!')
      })

      socket.on('user', (user) => {
        commit('setUser', user)
      })

      socket.on('rooms', (rooms) => {
        commit('setRooms', rooms)
      })

      socket.on('activeRoomId', (roomId) => {
        commit('setActiveRoomId', roomId)
      })

      socket.on('message', (message) => {
        commit('addMessage', message)
      })

      socket.on('clearMessages', () => {
        commit('clearMessages')
      })

      socket.on('disconnect', () => {
        console.log('Disconnected from server!')
      })
    },
    sendMessage({ state }, message) {
      const socket = io('http://localhost:3000')

      const payload = {
        roomId: state.activeRoomId,
        message
      }

      socket.emit('message', payload)
    }
  },
  modules: {
  }
})
Copy after login

In this example, we define an initial state, user information, session information, messages and notifications, etc. We have defined a series of mutations and actions for operating user information, session information, messages, notifications and other related states.

  1. Create Vue component

We can use Vue.js and Vuex Store to create a Chat component.

<template>
  <div class="chat">
    <div class="chat__user">
      <h2>{{ user.name }}</h2>
    </div>
    <div class="chat__rooms">
      <ul>
        <li v-for="room in rooms" :key="room.id" @click="selectRoom(room.id)">
          {{ room.name }}
        </li>
      </ul>
    </div>
    <div class="chat__messages">
      <ul>
        <li v-for="message in messages" :key="message.id">
          {{ message.text }}
        </li>
      </ul>
    </div>
    <div class="chat__input">
      <input type="text" v-model="message">
      <button @click="sendMessage()">Send</button>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  name: 'Chat',
  computed: {
    ...mapState(['user', 'rooms', 'activeRoomId', 'messages']),
  },
  methods: {
    ...mapActions(['connect', 'sendMessage', 'selectRoom']),
  },
  mounted() {
    this.connect()
  }
}
</script>
Copy after login

In this component, we use the v-for command to bind rooms and messages in a loop, use the v-model command to bind the input box, and use the @click command to bind the send button. We also use the mapState and mapActions functions to map the states and actions in the store to the component's computed properties and methods. When mounting the component, we call the connect method to initialize the Socket.io connection.

  1. Implementing Socket.io on the server side

We also need to implement Socket.io on the server side for use in Vue applications. Create a server using the following code:

const app = require('express')()
const http = require('http').createServer(app)
const io = require('socket.io')(http)

const PORT = 3000

http.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`)
})

let users = []
let rooms = []

io.on('connection', (socket) => {
  console.log('Client connected!', socket.id)

  socket.on('verifyUser', (user) => {
    console.log('Verifying user', user)

    const authenticatedUser = {
      id: socket.id,
      name: 'Mike'
    }

    socket.emit('user', authenticatedUser)
  })

  socket.on('getRooms', () => {
    socket.emit('rooms', rooms)
  })

  socket.on('selectRoom', (roomId) => {
    socket.join(roomId)
    socket.emit('activeRoomId', roomId)
    socket.emit('clearMessages')

    const room = rooms.find(room => room.id === roomId)
    socket.emit('messages', room.messages)
  })

  socket.on('message', (payload) => {
    const room = rooms.find(room => room.id === payload.roomId)

    const message = {
      id: Date.now(),
      text: payload.message
    }

    room.messages.push(message)

    io.in(payload.roomId).emit('message', message)
  })

  socket.on('disconnect', () => {
    console.log('Client disconnected!', socket.id)
  })
})

rooms.push({
  id: '1',
  name: 'Room 1',
  messages: []
})

rooms.push({
  id: '2',
  name: 'Room 2',
  messages: []
})
Copy after login

In this example, we create an HTTP server using Socket.io and listen for connection events on the server. We have defined various Socket.io events such as verifyUser, getRooms, selectRoom, message, etc.

We also added some initial rooms and users. For each client that connects to the server, we output a connection message; for each client disconnect event, we log a message. In the selectRoom event, we use the socket.join method to add the client to the room where we want to send the message. Finally, we use the Rooms array to store the data of all rooms, and use the component's selectRoom method to select the room to join.

4. Conclusion

By using the combination of Vue and Socket.io, you can easily build high-performance, real-time connected chat and instant messaging applications, which can ensure the real-time nature of data and greatly improve Improve user experience and data processing efficiency. Through the optimization of Vue and Socket.io, we can start development more quickly, quickly iterate versions, and the real-time and stability of data are better guaranteed.

The above is the detailed content of How to build real-time chat and instant messaging applications using Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to pass parameters for vue function How to pass parameters for vue function Apr 08, 2025 am 07:36 AM

There are two main ways to pass parameters to Vue.js functions: pass data using slots or bind a function with bind, and provide parameters: pass parameters using slots: pass data in component templates, accessed within components and used as parameters of the function. Pass parameters using bind binding: bind function in Vue.js instance and provide function parameters.

See all articles