1

I have custom service instances created in main.ts

app.config.globalProperties.$service1 = new Service1();
app.config.globalProperties.$service2 = new Service2();

I can use these instances inside vue components but I want to be able to use them in some utility files.

In vue 2 it was like:

import Vue from "vue";
Vue.prototype.$service1.someMethod("foo");

The only option that worked for me is to export the app instance in main.ts and importing it in my utility files but that did not look right.

What is the equivalent of Vue.prototype in Vue 3?

How to keep it singleton and still use the instances outside vue components?

  • perhaps you searched for the wrong thing ... [this](https://stackoverflow.com/questions/63100658/add-global-variable-in-vue-js-3) question and answer came up when I searched using the title you used in your question – Jaromanda X Jul 22 '22 at 09:59
  • 1
    This is XY problem. You shouldn't do what you try to do. If you have a service, just import it. – Estus Flask Jul 22 '22 at 10:03

1 Answers1

0

There are no good reasons for this code to be written in main.ts, then there won't be a necessity to get service instance frome a place it doesn't belong to.

With the benefits of modular JS, service instance can be defined in a module:

export default new Service1();

Then the service is imported in every module it's used:

import service1 from '.../service';

It's unnecessary to expose it to all component instances like it's done with Vue.prototype, the latter is the remnant of non-modular Vue that used Vue variable as global namespace. Currently the exposure of global dependencies through app.config.globalProperties is only needed for those that are supposed to be used in component templates, e.g. filters.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565