SoFunction
Updated on 2025-04-06

Detailed explanation of the latest syntax use of vue3.2 to implement instant messaging

It is a necessary plug-in for instant messaging, and it must be used in conjunction with the backend. The front-end uses [-client], aiming to avoid detours~

Install [-client] first

yarn add -client -S

After installation, create new ts and introduce them as plug-in

Create a new one under the utils folder

The code is as follows

// New ts is introduced as plug-inimport io from '-client';
export default {
  install: (app: any, { connection, options }) => {
    const socket = io(connection, options);
    .$socket = socket;
    ('socket', socket);
  },
};

Introduced

import SocketIO from '/@/utils/socket';
// socket
// Configurationconst socketOptions = {
  autoConnect: true, // Automatic connection  transports: ['websocket'], // Specify as a websocket connection  reconnect: true,
  reconnectionAttempts: 5, // Number of reconnections};
(SocketIO, {
  connection: 'wss://yyds.',
  options: socketOptions,
});

Execute login method on the socket on the link

On the general linksocketTo execute aLog inMethod, this method is usually called once, so you have to choose to be in the appropriate location, that is, you must call it immediately after logging in. When vue2, you can perform login operations in the getInfo interface in vuex, but in vue3 this pointing is more difficult to do, and it is used again.pinia, it's not easy to do, so we choseExecute the login method in

The code is as follows

The project is used【pinia

<script setup lang="ts">
  /** Execute socketio login. If you don’t understand, add me v 1115009958 for communication*/
  import { computed } from 'vue';
  import { useUserStore } from '/@/store/modules/user';
  const socket: any = inject('socket');
  const userStore = useUserStore();
  const getUserInfo = computed(() => {
    const { info } = userStore.$state;
    return info;
  });
  watch(getUserInfo, (newVal) => {
    ('login', {
      nickname: ,
      _id: newVal._id,
    });
  });
</script>
  • ps: watch monitor isMake sure getUserInfo can read the data in $state, call again('login')method

Trigger emit, on method

If you want to triggeremit、onMethod, do this in the page

<script setup lang="ts">
  /** Use inject communication method to receive socket instance*/
  const socket: any = inject('socket');
  // Use on to listen for events  ('message', (res: any) => {
      ('Received Data', res);
  });
  // Use emit to send events  ('sayTo',{ message:"test" });
</script>

The above is the detailed explanation of the latest syntax use of vue3.2 to implement instant messaging. For more information about vue3.2 instant messaging, please follow my other related articles!