1

I have a Vue 3 app and an express server. The server does not serve any pages just acts as an API so no socket.io/socket.io.js file is sent to client. I am trying to set up socket.io in one of my vue components but whatever I try does not work. Using vue-3-socket.io keeps giving 't.prototype is undefined' errors.

I have tried vue-socket.io-extended as well with no luck.

Any advice would be appreciated as to the reason and solution for the error above, I have tried various SO solutions without success, and the best way forward.

1 Answer 1

1

You can use socket.io-client. I have used socket.io-client of 4.4.1 version.

step: 1 Write class inside src/services/SocketioService.js which returns an instance of socketio.

import {io} from 'socket.io-client';

class SocketioService {
    socket;
    constructor() { }

    setupSocketConnection() {
        this.socket = io(URL, {
            transports: ["websocket"]
        })

        return this.socket;
    }
}

export default new SocketioService();

Step 2: Import SocketioService in App.vue. You can instantiate in any lifecycle hook of vue. I have instantiated on mounted as below. After instantiation, I am listening to welcome and notifications events and used quasar notify.

<script>
import { ref } from "vue";
import SocketioService from "./services/socketio.service.js";

export default {
  name: "LayoutDefault",
  data() {
    return {
      socket: null,
    };
  },
  components: {},

  mounted() {
    const socket = SocketioService.setupSocketConnection();
    socket.on("welcome", (data) => {
      const res = JSON.parse(data);
      if (res?.data == "Connected") {
        this.$q.notify({
          type: "positive",
          message: `Welcome`,
          classes: "glossy",
        });
      }
    });

    socket.on("notifications", (data) => {
      const res = JSON.parse(data);

      let type = res?.variant == "error" ? "negative" : "positive";
      this.$q.notify({
        type: type,
        message: res?.message,
        position: "bottom-right",
      });
    });
  },
};
</script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.