Vue3 – Global Socket.io Installation (in all components)

src/main.js

import { createApp } from 'vue'
import App from './App.vue'
import .....
import io from 'socket.io-client';

const app =  createApp(App);
app.config.globalProperties.$soketio = io('YOUR-SOCKET-IO-SERVER-HOSTNAME-WITH-PORT');
app.use(store).use(router).mount('#app')

Listening example in Vue Component

<template>
<div>
  <ol class="list-group list-group">
    <li class="list-group-item d-flex justify-content-between align-items-start"
        v-for="(message,index) in messages" :key="index">
      <div class="ms-2 me-auto">
        {{ message.message }}
      </div>
    </li>
  </ol>
 </div>
</template>

<script>

export default {
  name: "Message",
  data() {
    return {
        messages: []
    }
  },
  created() {
    this.$soketio.on('new-message', (data) => {
      this.messages.push(data);
    })
  }
}
</script>

Emit example in Vue Component

<template>
  <div class="thing">
    <button @click="makeSomething">makeSomething</button>
  </div>
</template>

<script>

export default {
  name: 'User',
  data() {
    return {
    }
  },
  methods: {
    makeSomething(){
      this.$soketio.emit('remove-user', this.user);
    }
  },
}
</script>

Views: 2700