DEV Community

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

Posted on

Vue 3 Composition API +

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

If you want to use you can search 'vue 3' and find 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 directly, without Vue plugin:

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


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

But why not just export socket from 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.

Top comments (1)

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: