Home > Web Front-end > Vue.js > body text

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

WBOY
Release: 2023-06-27 17:44:51
Original
1438 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template