1

I have this class for sockets. Is there any way that I could make this globally accessible? I'd like to access the functions anywhere in my app for example like $socket.methodName()

What I've tried

class InitSocket {
  constructor(options) {
    this.options = options;
  }

  connect() {
    console.log(this.options);
  }
}

export default {
  install: (Vue, options) => {
    Vue.prototype.$socket = new InitSocket(options);
  },
};

in main.js

const { createApp } = require('vue');
import App from "./App.vue";
import Sockets from './plugins/Socket'

const app = createApp(App);
app.use(Sockets , "test");
app.mount("#app");

But I am getting this message Cannot set properties of undefined (setting '$socket') - What am I doing wrong?

Dave
  • 1
  • 1
  • 9
  • 38
  • Does this answer your question? [Add global variable in Vue.js 3](https://stackoverflow.com/questions/63100658/add-global-variable-in-vue-js-3) – Estus Flask Mar 04 '22 at 10:52
  • Also it's a bad practice in Vue 3. There's not much use of $socket in templates, and in composition API there's no `this`. Just import it where you use it. – Estus Flask Mar 04 '22 at 10:54
  • @EstusFlask but what if I have to use it in 20 components, I do not want to import it everywhere. – Dave Mar 04 '22 at 11:04
  • That's how modern JS works. IDEs handle imports for you. You'll have to do this any way with composition API. In order to not import it and use like `$socket.methodName()` (no `this`) you'd have to assign it to `window`, which is an absolute no-no. – Estus Flask Mar 04 '22 at 11:28

1 Answers1

0

In Vue 3 you can have multiple apps and you can no longer add to Vue prototype.

In order to write and use a plugin, follow the steps:

Step 1: Create the plugin

export default {
  install: (app, options) => {
    class InitSocket {
      constructor(options) {
        this.options = options;
      }

      connect() {
        console.log(this.options);
      }
    }
    
    // inject a globally available $socket() method
    app.config.globalProperties.$socket = new InitSocket(options)
  }
}

Step 2: Import and install it in main.js

import { createApp } from 'vue'
import App from "./App.vue";
import Sockets from './plugins/Socket'

const app = createApp(App);
app.use(Sockets , "test");
app.mount("#app");

Read more on the Vue docs: Plugins

Roland
  • 24,554
  • 4
  • 99
  • 97