Vuereact & vue & angular

vue3.2最新语法如何使用socket.io实现即时通讯

2023-03-23  本文已影响0人  风中凌乱的男子

socket.io是即时通讯必需的插件,要和后端配合使用socket.io才可以,前端使用【socket.io-client】,旨在让你少走弯路~

yarn add socket.io-client -S
// 新建ts 以插件形式引入
import io from 'socket.io-client';
export default {
  install: (app: any, { connection, options }) => {
    const socket = io(connection, options);
    app.config.globalProperties.$socket = socket;
    app.provide('socket', socket);
  },
};
import SocketIO from '/@/utils/socket';
// socket
// 配置
const socketOptions = {
  autoConnect: true, // 自动连接
  transports: ['websocket'], // 指定为websocket连接
  reconnect: true,
  reconnectionAttempts: 5, // 重连次数
};
app.use(SocketIO, {
  connection: 'wss://yyds.it98k.cn',
  options: socketOptions,
});
<script setup lang="ts">
  /** 执行socketio登录 看不懂的加我v 1115009958 交流*/
  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) => {
    socket.emit('login', {
      nickname: newVal.nickname,
      _id: newVal._id,
    });
  });
</script>
<script setup lang="ts">
  /** 使用inject通信方法接收socket实例*/
  const socket: any = inject('socket');
  // 使用on监听事件
  socket.on('message', (res: any) => {
      console.log('接收到的数据 ', res);
  });
  // 使用emit发送事件
  socket.emit('sayTo',{ message:"test" });
</script>
上一篇 下一篇

猜你喜欢

热点阅读