vue-decorator-inject
Dependency injection with ES6 decorators for Vue.js
Installation
If you are using Webpack or similar:
npm i --save-dev vue-decorator-inject
Otherwise --save
is probably more sensible.
Introduction
This library combines a container with an interface similar to containers in Symfony with the concept of abstract symbols as keys in your container. This way autocompletion features in your IDE can be fully used. Additionally dependency injection can be done by using decorators to make your application as readable as possible.
Design and usage
Read the documentation for vue-class-component beforehand. This package is based upon it.
Define your abstract types first, later you bind your concrete classes etc. to them.
// types.jsComponentA: Symbol'ComponentA'ComponentB: Symbol'ComponentB'MyService: Symbol'MyService'MyFactory: Symbol'MyFactory'SomeConstant: Symbol'SomeConstant'
Define your components, inject your dependecies.
@Component@@myService@generatedFromTheFactory
Implement your services and factory functions. In services you can either let dependencies be injected into the constructor or get them by using @Inject
.
// MyService.js{// do stuff}// MyFactory.js// ... import statements ...{// do stuff, create an instance using MyServicereturn someInstance;}
And finally tie it all together with your dependency configuration.
// config.js// import all other dependencies// use 'set' for constants or class definitionsContainerContainer// use 'register' to register class definitions, which have to be instantiated// (with optional dependencies)Container// use 'factory' to register factory functions (with optional dependencies)Container
Important implementation hint: always include the config.js
file as early as possible in your project.
// main.js// other imports// Your typical root component@@{}el: '#app'
In the above example @Inject
is used on an object field to inject your routing definition for vue-router
. You can define your routing definition by using a factory.
// router.jsVue{return// your route definitions}// config.jsContainer