How to use reflection in Vue.js?

594 views Asked by At

I have a case where I'm receiving a message from signalr and I'm trying to instantiate a object based on a name that I get in the message.

I had a similar case in angularjs where we solved it using an $injector that has $injector.get("Name") which returns an object that I need.

1

There are 1 answers

5
Estus Flask On BEST ANSWER

Vue provides no DI container that can help with this. Basically there should be a map that links classes or factory functions to string identifiers:

const servicesMap = {
  Foo,
  Bar
};

...

if (!Object.keys(servicesMap).includes(name))
  throw ...

const Service = servicesMap[name];
const service = new Service();

Considering that services can be imported from a single folder, this can be done with dynamic imports:

const Service = require(`.../services/${name}`).default;
const service = new Service();

This depends on project setup and automatically disables treeshaking for services.