DEV Community

Даниил Пронин
Даниил Пронин

Posted on

Vue 3 Composition API + socket.io

Migrating from Vue 2 to Vue 3, you might want to start using Composition API.

If you want to use socket.io you can search 'vue 3 socket.io' and find vue-3-socket.io. You will see following in it's readme:

this.sockets.subscribe('EVENT_NAME', (data) => {
    this.msg = data.message;
});
Enter fullscreen mode Exit fullscreen mode

But Vue 3 Composition API is about to use setup() or <script setup> and there's no this.

So you have to use socket.io directly, without Vue plugin:

socket.io.js

export const useSocketIO = () => {
    const socket = io('ws://localhost:3000')
    return {
        socket,
    }
}
Enter fullscreen mode Exit fullscreen mode

MyComponent.vue

<script>
import { defineComponent } from 'vue'
export default defineComponent({
    setup() {
        const { socket } = useSocketIO()
        socket.on('welcome', () => { console.log('welcome') })
    }
})
</script>
Enter fullscreen mode Exit fullscreen mode

But why not just export socket from socket.io.js and import it in a component? If I do that, I can emit events but cannot subscribe on them. Maybe it's because I use Quasar 2 with SSR mode.

Discussion (1)

Collapse
kissu profile image
Konstantin BIFERT

You are not obliged to use the Composition API, you can also use the Options API with Vue3. Otherwise, yeah making a homemade vanilla solution is still the best way to go IMO.

Related SO question: stackoverflow.com/q/71466297/8816585