Dependency Injection for vue
npm install vue-inject --save-dev
// main.js
import injector from 'vue-inject';
import Vue from 'vue';
Vue.use(injector);
// myService.js
import injector from 'vue-inject';
class MyService{
// ...
}
injector.service('myService', MyService);
// myComponent.vue
<script>
export default {
dependencies : ['myService'],
components : ['MyChildComponent'],
directive : ['myDirective'],
methods : {
foo(){
return this.myService.something();
}
}
}
</script>
Example:
/
main.js
app.vue
app_start.js
constants.js
services.js
// main.js
import Vue from 'vue';
import injector from 'vue-inject';
import App from './app';
// app_start will load anything that can be injected into your application
require('./app_start');
// register the injector with Vue
Vue.use(injector);
// render the main component
new Vue({
render : h => h(App)
});
// app_start.js
require('./constants');
require('./services');
// By requiring these files, the factories and services will be registered with the injector.
// You could just export the factory functions and register them all here, but this would mean
// separating the function from the array of dependencies it uses.
// constants.js
import injector from 'vue-inject';
import axios from 'axios';
injector.constant('apiRoot', 'http://www.fake.com/api');
injector.constant('axios', axios);
// services.js
import injector from 'vue-inject';
function apiUrlBuilder(apiRoot){
return function(path){
return apiRoot + '/' + path;
}
}
injector.factory('apiUrlBuilder', 'apiRoot', apiUrlBuilder);
function api(apiUrlBuilder, axios){
this.get(path){
var url = apiUrlBuilder(path);
return axios.get(url);
};
}
injector.service('api', ['apiUrlBuilder', 'axios'], api);
// app.vue
<template>
<div>...</div>
</template>
<script>
export default {
dependencies : 'api',
data(){
return {
stuff : null
};
},
created(){
// api has been injected in by vue-inject
this.api.get('stuff').then(response => this.stuff = response.data);
}
};
</script>
The injector is used to register dependencies that can then be injected into a component.
var injector = require('vue-inject');
The injector must be regstered on the Vue class:
Vue.use(injector);
You can supply an options object to determine which properties will be injected.
Vue.use(injector, { dependencies: true, mixins: true, directives: true, components: true });
By default only dependencies
is enabled.
Registers a service. A service takes a constructor function (or an ES6 class). When a service is injected into a component, the constructor is instantiated.
The dependencies option determine which dependencies to inject into the constructor. These will be passed into the function in the same order.
injector.service('myService', ['injected'], function(injected){
this.foo = () => {};
});
Registers a factory. When injected, the function is called and the return value is then passed into the component.
Similarly to the service
type, any dependencies are injected into the function parameters.
injector.factory('myFactory', ['injected'], function(injected){
return {
foo : () => {}
};
});
Registers a constant value.
injector.constant('myConstant', { foo : 'bah' })
Registers a decorator. A decorator allows you to modify an existing factory. The return value of the function is then used as the resolved factory.
injector.decorator('myFactory', function (myFactory) {
myFactory.foo = 'decorated';
return myFactory;
});
Component dependencies are calculated automatically, however, there may be times when you want to use a dependency outside of a component. This allows you to pull a dependency directory from the injector. The value is resolved in exactly the same way.
var myService = injector.get('myService');
myService.doStuff();
The namedDependencies parameter accepts an object with custom values for a dependency. For example: if your factory depends on an apiUrl constant, you can overwrite the value of that constant by passing in a new value.
var myService = injector.get('myService', { apiUrl : 'localhost:3000/' });
myService.createUrl('foo') === 'localhost:3000/foo';
Removes all registered factories from the injector.
Once a dependency has been injected, its value is cached (see lifecycles below). Usually this is fine, as most factories will be stateless. However sometimes it is necessary to recalculate a factory, such as when unit testing. Clear cache sets all registered factories to an unresolved state. The next time they are injected, the values will be recalculated.
injector.factory('obj', () => { return {}; });
var a = injector.get('obj');
var b = injector.get('obj');
a === b; // true
injector.clearCache();
var c = injector.get('obj');
a === c; // false
If you have multiple Vue applications, you can create a new injector using spawn
.
let injector2 = injector.spawn();
By default this will create a brand new injector, but if you want to share registered services/factories between the two, pass true
into the function. This will create a new injector that inherits the previous one. Any factories registered on the first injector will be available to the second, but not vice versa.
If set to false
then all dependencies will be made optional. If a component's dependency cannot be found, rather than throwing an error it will just be set to undefined
. Not that this does not affect the get
function.
(
dependencies?: Array<string>,
fn: (...deps) => Function
)
Encase allows you to wrap any function in an outer function. This allows you to inject dependencies (at runtime) but the original function signature will remain the same.
In the context of a Vue application, this method comes into its own when writnig Vuex actions. For example, the following action:
import axios from 'axios';
const actions = {
FETCH: ({ commit }) => {
axios.get('/my/api').then((response) => {
commit('FETCHED', response.data);
});
},
};
can be rewritten as:
const actions = {
FETCH: encase([ 'axios' ], (axios) => ({ commit }) => {
axios.get('/my-api').then((response) => {
commit('FETCHED', response.data);
});
}),
};
now this does add a little more code to the function, but it means we've got proper dependency injection per action! And Vuex doesn't even need to know about it.
When registering a factory or service, it's possible to determine the lifecycle.
As of v0.4, the default lifecycle is set to class
.
Caches the value the first time the factory is injected. This value is then re-used every time.
injector.factory('myFactory', fn).lifecycle.application();
Never caches the value. Every time the factory is injected, the value is recalculated.
injector.factory('myFactory', fn).lifecycle.none();
Caches the value against the current injector. If you have multiple injectors, the value will be cached against the current injector only, any other injectors will have to recalculate its value.
injector.factory('myFactory', fn).lifecycle.class();
There are number of ways you can inject a dependency into a Vue component:
The most common way is to declare your dependencies on the component:
export default {
data(){},
computed : {},
methods : {},
dependencies : ['myFactory']
};
The dependencies
property accepts either a string, an array, or an object:
For each string in the array, the injector will find the corresponding factory and inject it into the component.
dependencies : ['dep1', 'dep2', 'dep3']
This is the same as supplying an array with a single element.
An object allows you to specify an alias for a factory.
dependencies : { myAlias : 'myFactory' }
then in your component you can access the injected myFactory instance via this.myAlias
.
For the following methods, you must enable their related options when calling Vue.use
If you register components on the injector you can then inject them into the components property:
components : { myComponent : 'injectedComponent' }
The same is true for directives:
directives : { myDirective : 'injectedDirective' }
You can also add a dependencies
object to Vue's prototype
. These dependencies will then be injected into every component.
Vue.prototype.dependencies = ['myService'];
The injector comes bundled with jpex-web and jpex-defaults, meaning that you have access to the following factories automatically:
Performs either a deep or shallow copy of an object.
$copy(obj); // shallow copy
$copy.shallow(obj); // shallow copy
$copy.deep(obj); // deep copy
$copy.extend(newObj, obj, obj2); // Deep copies obj2 and obj into newObj.
Returns the type of an object. This goes further than typeof
in that it differentiates between objects, arrays, dates, regular expressions, null, etc.
var t = $typeof('hw'); // 'string'
Wraps the console functions.
$log('log');
$log.log('log');
$log.warn('warning');
$log.error('Error');
Wraps up the Promise class and includes a simple polyfill implementation if needed. It exposes all of Promise's static methods i.e. resolve
, reject
, all
, and race
.
return $promise((resolve, reject) => {});
Equivalent of injector.get()
.
Equivalent of setTimeout()
.
Equivalent of setInterval()
.
Equivalent of setImmediate()
or setTimeout(fn, 0)
.
Injects the global window object.
Injectors the global document object;
As vue-inject is built from jpex, the Jpex API is fully available for additional configuration. You can even manually create an injector with custom settings using Jpex's extend
method:
const injector = vueInject.extend({
defaultLifecycle : 1 // application
// more config options...
});