MetinSeylan / Vue-Socket.io

😻 Socket.io implementation for Vuejs and Vuex
https://metin.sh
MIT License
3.95k stars 495 forks source link

Vue3 composition API documentation #304

Open djcaesar9114 opened 3 years ago

djcaesar9114 commented 3 years ago

It would be great to add documentation on how implement Vue-Socket.io with VueJS 3 composition API.

athamour1 commented 2 years ago

But how do you use composition API in this package ???

liquidvisual commented 2 years ago

Is it even compatible with V3?

john-yick commented 2 years ago

This package is not compatible with Vue3, there is a fork of this package that was updated to vue3 but uses the 2.x version for socket.IO.

In the end gave up and there is a much simpler solution, by importing the socket.io-client directly and creating a smaller plugin wrapper to load it into the globalProperties. You can then carry on using it as you would with this package.

main.ts

app.use(vueSocketIOClient, {
    connection: 'http://localhost:7600',
})

vueSocketIOClient.ts

import { App, Plugin } from "vue";
import { io } from "socket.io-client";

const vueSocketIOClient: Plugin = {
    install: async (app: App, options: any): Promise<void> => {
        app.config.globalProperties.$socket = io(options.connection, options)
    }
}
export { vueSocketIOClient };
athamour1 commented 2 years ago

Apparently you can use it somehow, i dont know how a good way to use it but in quasar framework i have created a bootfile like this:

import { boot } from 'quasar/wrappers'
import VueSocketIO from 'vue-socket.io'
import SocketIO from 'socket.io-client'
// "async" is optional;
// more info on params: https://v2.quasar.dev/quasar-cli/boot-files
export default boot(async ({app, store, router}) => {
  // something to do
  const connection = SocketIO('https://your.server.com')
  const socket = new VueSocketIO({
    debug: true,
    connection: connection, //options object is Optional
    vuex: {
      store,
      actionPrefix: "SOCKET_",
      mutationPrefix: "SOCKET_"
    }
  })
  app.use(
    socket
  );
  app.provide('socket', connection)
})

and then in the composition api i call it with injection like this

import { defineComponent, inject } from 'vue';

and inside the setup() function

const socket = inject('socket')
socket.emit('event', payload)