繁体   English   中英

如何在 vue.js 中使用组合为 api 的 vue-3-socket.io?

[英]how to use vue-3-socket.io with composition api in vue.js?

我如何访问vue.js组件中设置 function 中的套接字实例

我使用vue-3-socket.io

在我的main.js


import VueSocketIO from 'vue-3-socket.io'
import SocketIO from 'socket.io-client'

Vue.use(new VueSocketIO({
    debug: true,
    connection: SocketIO('http://metinseylan.com:1992', {}), 
    vuex: {
      store,
      actionPrefix: "SOCKET_",
      mutationPrefix: "SOCKET_"
    }
  })
);

我将直接使用 socket.io,不使用 Vue 插件:

export const useSocketIO = () => {
    const socket = io('http://metinseylan.com:1992')
    return {
        socket,
    }
}

Component

<script setup>
import { defineComponent } from 'vue'

const { socket } = useSocketIO()
socket.on('welcome', () => { console.log('welcome') })
  
</script>

我首先使用了@kissu ( https://stackoverflow.com/a/72400545/3475778 ) 的答案,但我发现这有问题,因为它创建了多个 socketIO 连接,这不是你想要的(例如发送给所有人,除了发件人不会按预期工作,因为您将通过我们客户端的其他连接接收消息)

我现在的方法是创建 class 的 object 并导入 object 而不是 class 本身。

src/services/socketio.service.ts

import type { Socket } from "socket.io-client";
import { io } from "socket.io-client";
import type { ClientToServerEvents, ServerToClientEvents } from "../communication";

class SocketIOService {
  socket: Socket<ServerToClientEvents, ClientToServerEvents>;
  constructor() {
    this.socket = io(process.env.VUE_APP_SOCKET_ENDPOINT || "http://localhost:3000" );
  }
}

// create an instance/connection here
export const socket = new SocketIOService().socket;

src/components/myButton.vue

<script setup lang="ts">
// import the object instead of the class
import { socket } from "../services/socketio.service";

async function buttonPress() {
  socket.emit("buttonPressed");
}
</script>

多个组件现在将共享相同的 socketio 连接:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM