[VueJS + Typescript] Decouple Dependencies Using IoC Containers in Vue with TypeScript and InversifyJS
Using Object Oriented Programming, OOP, style allows us to apply Inversion of Control, IoC, and more patterns. An IoC container helps decoupling dependencies by using a class constructor or properties to identify and inject its dependencies. This lesson will show you how can you create and use an IoC container to decouple an http client and users service dependencies in a Vue component with TypeScript and InversifyJS.
When you are using Class, you also need to mantain the singleton of Class. Use can use similiar approach as Angular in VueJS as well.
Install:
npm i --save inversify reflect-metadata inversify-inject-decorators
Modify tsconfig.json:
{
"compilerOptions": {
"lib": [
"dom",
"es5",
"es2015"
],
"module": "es2015",
"moduleResolution": "node",
"target": "es5",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true
}
}
main.ts:
import "reflect-metadata"
import "core-js/es6/map"
import "core-js/es6/symbol" import Vue from 'vue'
import App from './App.vue' Vue.config.productionTip = false /* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
components: { App }
})
Tip: If you want to create unqiue String, you can use Symbol('UserService'), it is useful tool.
Create a container.ts, which contains all the singleton services:
import {Container} from 'inversify';
import {UsersService} from './user-service';
import {HttpClient} from './http-client';
import {TYPES} from './types';
import getDecorators from 'inversify-inject-decorators';
const container = new Container();
container.bind<UserService>(TYPES.UsersService).to(UsersService);
container.bind<HttpClient>(TYPES.HttpClient).to(HttpClient);
// Lazy inject is good for props
const {lazyInject} = getDecorators(container);
export {container, lazyInject}
Create types.ts:
export const TYPES = {
UsersService: Symbol('UsersService'),
HttpClient: Symbol('HttpClient')
}
http-client.ts:
From:
export class HttpClient {
get(url: string): Promise<any> {
return fetch(url).then(data => data.json())
}
}
To:
import {injectable} from 'inversify';
@injectable()
export class HttpClient {
get(url: string): Promise<any> {
return fetch(url).then(data => data.json())
}
}
user-service.ts:
From:
export class UsersService {
private http: HttpClient;
constructor() {
this.http = new HttpClient()
}
getUsers(): Promise<any> {
return this.http.get('https://jsonplaceholder.type');
}
}
To:
import {inject, injectable} from 'inversify';
import {TYPES} from './types';
@injectable()
export class UsersService {
constructor(@inject(TYPES.HttpClient) private http) {
}
getUsers(): Promise<any> {
return this.http.get('https://jsonplaceholder.type');
}
}
Then we can use UsersService in App.vue:
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import { lazyInject } from './container'
import { TYPES } from './types'
@Component
export default class App extends Vue {
users = []
@lazyInject(TYPES.UsersService)
usersService
created() {
this.usersService.getUsers()
.then(data => {
this.users = data
})
}
}
</script>
[VueJS + Typescript] Decouple Dependencies Using IoC Containers in Vue with TypeScript and InversifyJS的更多相关文章
- IoC Containers with Xamarin
When writing cross platform apps with Xamarin, our goal is share as close to 100% of our code across ...
- vue与TypeScript集成配置最简教程
https://blog.csdn.net/u014633852/article/details/73706459 https://segmentfault.com/a/119000001187808 ...
- Vue Cli3 TypeScript 搭建工程
Vue Cli3出来也一段时间了,我想尝试下Vue结合TypeScript搭建个工程,感受下Vue下用TS...网上有一篇讲的非常详细的教程 vue-cli3.0 搭建项目模版教程(ts+vuex+ ...
- MVVMLight - IOC Containers and MVVM
在面向对象编程的早期,开发者要面对在应用程序或者类库中创建或检索类的实例的问题.针对这个问题有很多的解决方案.在过去几年中,依赖注入(DI)和控制反转(IoC)在开发者中很流行,并且取代了老的方案,比 ...
- Vue使用Typescript开发编译时提示“ERROR in ./src/main.ts Module build failed: TypeError: Cannot read property 'afterCompile' of undefined”的解决方法
使用Typescript开发Vue,一切准备就绪.但npm start 时,提示“ ERROR in ./src/main.tsModule build failed: TypeError: Cann ...
- Vue + WebPack + Typescript初学者VSCode项目 (按需加载、跨域调试、await/async)
万事开头难,一个好的Hello World程序可以节省我们好多的学习时间,帮助我们快速入门.Hello World程序之所以是入门必读必会,就是因为其代码量少,简单易懂.但我觉得,还应该做到功能丰富, ...
- [TypeScript] Query Properties with keyof and Lookup Types in TypeScript
The keyof operator produces a union type of all known, public property names of a given type. You ca ...
- [TypeScript] Collect Related Strings in a String Enum in TypeScript
As of TypeScript 2.4, it is now possible to define string enums, or more precisely, enums with strin ...
- [Vue + TS] Create your own Decorators in Vue with TypeScript
We’ve used @Watch, @Inject and more decorators from vue-property-decorator. In this lesson however w ...
随机推荐
- opencv-flag
http://blog.csdn.net/yiyuehuan/article/details/43701797 在Mat类中定义了这样一个成员变量: /*! includes several bit- ...
- 迅为嵌入式开发板iTOP-6818开发板八核Cortex-A53架构,满足各种产品需求
性价比更高 内存:1G(可选2G);存储:16G;4418:四核 Cortex-A9;6818:八核Cortex-A53. 功能更强 板载4G(全网通),GPS,WIFI,千兆以太网,重力加速度计等, ...
- leetcode_Counting Bits_dp
给定num,用O(num)的时间复杂度计算0--num中所有数的二进制表示中1的个数. vector<int> countBits(int num) { vector<,); ;i& ...
- 「Python调试器」,快速定位各种疑难杂症!!
现在很多的编辑器其实都带着「调试程序」的功能,比如写 c/c++ 的 codeblocks,写 Python 的 pycharm,这种图形界面的使用和显示都相当友好,简单方便易学,这个不是我这篇文章要 ...
- Java IO(一)--File类
File类不是单指文件,它既可以代表一个文件名称,又可以代表一个目录下的一组文件.可以用来创建.删除.遍历文件等 public static void main(String[] args) { St ...
- 模板—trie图
做了某题之后发现trie的AC自动机太垃圾了,动不动就TLE,然后我就去学了trie图. #include<iostream> #include<cstdio> using n ...
- python3+beautifulSoup4.6抓取某网站小说(一)爬虫初探
本次学习重点: 1.使用urllib的request进行网页请求,获取当前url整版网页内容 2.对于多级抓取,先想好抓取思路,再动手 3.BeautifulSoup获取html网页中的指定内容 4. ...
- [python] 时间序列分析之ARIMA
1 时间序列与时间序列分析 在生产和科学研究中,对某一个或者一组变量 进行观察测量,将在一系列时刻 所得到的离散数字组成的序列集合,称之为时间序列. 时间序列分析是根据系统观察得到的时间序列数据, ...
- JS授权
(function(){ var origin_url = location.href; var oauth_url = 'https://vx.mcilife.com/weixin/api/oaut ...
- margin负值应用
我理解的最关键的一点是: 在文档流中,只能是后面的流向前面的,即文档流只能向左或向上流动,不能向下或向右移动.第二个元素的基准线是第一个元素的右边界,第三个元素的基准线是第一.二个元素排好后最右边的边 ...