DEV Community

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

Posted on

10 3

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs