vue-socket.io-extended: socket within setup() // composition API

94 views Asked by At

In my vite/vue application I am trying to emit a message to socket-io from within a function defined in the setup () section / composition API.

I am able to successfully do so in the methods() section, but I have not figured how, within the setup() section, I can leverage the socket specified in the main.ts.

I feel I'm almost there.. any pointers highly appreciated. Thanks all for your time.

vue-file:

<template>
  <q-page>
    <q-btn label="send Message via Methods (Works)" @click="sendMessage_1()" color="green"></q-btn>&nbsp;
    <q-btn label="send Message via Setup (not Working)" @click="sendMessage_2()" color="red"></q-btn>&nbsp;
  </q-page>
</template>

<script lang="ts">
export default {
  methods: {
    async sendMessage_1() {
      console.log('Sending message 1');
      this.$socket.client.emit('message','TEST'); // WORKS! Comes through to the backend
      console.log('Sent message 1');
    },    
  },

  setup () {
    function sendMessage_2 () {
      console.log('Sending message 2');
      this.$socket.client.emit('message','TEST1'); // DOES NOT WORK (obv. because "this" does not exist in setup().. could not figure out how to write it differently)
      console.log('Sent message 2');
    }
    return {sendMessage_2}
  },
};

</script>

main.ts:

import App from './App.vue';
import VueSocketIOExt from 'vue-socket.io-extended';
import io from 'socket.io-client';
import { createApp } from 'vue';
import { Quasar, Notify } from 'quasar';
import router from './router/routes.js';

// Import icon libraries & Quasar css
import '@quasar/extras/material-icons/material-icons.css'
import 'quasar/src/css/index.sass'
 
const app = createApp(App);
app.use(VueSocketIOExt, io('', {path: '/absproxy/3000/socket.io/'}));
app.use(Quasar, {plugins: {Notify},});
app.use(router);
app.mount('#app');

Relevant packages:

vite: 4.4.5
vue: 3.3.4
socket.io-client: 4.7.2
vue-socket.io-extended: 5.0.0-alpha.5
1

There are 1 answers

0
Benjamin On

It seems that composition API is not yet supported by vue-socket.io-extended, since the developer maintaining it is in the war at Ukraine :-(

I was able to figure out my problem though, by using classic socket.io, using the solution explained here.

The only thing I had to change compared to the solution provided by kissu/capitalg is to use "'~/communication';" rather than "'../communication';", based on the guidance I found here.