Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

how can i access the socket instance inside the setup function in vue.js component

i use vue-3-socket.io

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

like image 876
mod7ex Avatar asked Nov 03 '25 12:11

mod7ex


2 Answers

I will use socket.io directly, without Vue Plugin:

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>
like image 60
fchancel Avatar answered Nov 05 '25 09:11

fchancel


I first used the answer by @kissu (https://stackoverflow.com/a/72400545/3475778) but I found this problematic as it creates multiple socketIO connections which is not what you want (e.g. send to everyone except the sender will not work as expected because you will receive the message via the other connections of our client)

My approach now is creating an object of the class and import the object instead of the class itself.

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>

Multiple components will now share the same socketio connection :)

like image 39
capitalg Avatar answered Nov 05 '25 09:11

capitalg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!