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

问题描述 投票:0回答:3

我如何访问

vue.js
组件中设置函数中的套接字实例

我用

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_"
    }
  })
);

javascript vue.js socket.io
3个回答
6
投票

我将直接使用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>

4
投票

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

我现在的方法是创建类的对象并导入该对象而不是类本身。

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>

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


0
投票

输入“通讯”?有例子吗?

© www.soinside.com 2019 - 2024. All rights reserved.