0

I'm building an app with a chat right now using Socket.IO and I have a counter of how many users are connected

My problem is that when only one user is connected, the counter shows 3. Why 3 ? Because I have 3 components and I'm importing socket.io-client in each of those like that

import io from "socket.io-client";
const socket = io();

export default {
   // bla bla bla
}

How can I import it once and make it available everywhere in my app ? I tried to import it in main.js then using it like

import { io } from 'socket.io-client';
createApp(App)
  .use(io)
  .mount("#app");

But in my components when I do const socket = io() it's considered not defined

  • @Dan It does but I can't manage to use both solutions... Why do they pass an object inside createApp and why do they use "Vue" instead of just createApp as the default ? –  Dec 15 '20 at 20:36
  • You can continue to pass your `App` object to the method. I'm not sure why they show an empty object like that in the [docs](https://v3.vuejs.org/guide/migration/global-api.html#vue-prototype-replaced-by-config-globalproperties) but I just changed it in the linked answer – Dan Dec 15 '20 at 20:50
  • 1
    @Dan I made it work, thank you a lot!! I was doing it [wrong](https://image.noelshack.com/fichiers/2020/51/2/1608066202-image.png) ahah –  Dec 15 '20 at 21:07

1 Answers1

0

You can make it available for all your components by adding it as an instance property.

For VuejS 3

In your main.js

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

const app = createApp(App)
app.config.globalProperties.$soketio = soketio
app.mount("#app")

For VuejS 2

In your main.js

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

Vue.prototype.$soketio = soketio;
new Vue({ render: h => h(App) }).$mount('#app')

In any component, you can access it using "this", like any other instance property for both Vuejs 2 and Vuejs3

this.$soketio ...

For more details see Vuejs 3.x Global API.

For more details see Vuejs 2.x Instance Properties.

Good luck.

tony19
  • 125,647
  • 18
  • 229
  • 307
MAW
  • 923
  • 8
  • 23