[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 ...
随机推荐
- PPTP的搭建
一.准备 1.检查是否支持pptp modprobe ppp-compress-18 && echo yes yes支持 2.是否开启tun cat /dev/net/tun 返回ca ...
- C#斐波那契数列递归算法
public static int Foo(int i) { if (i < 3) { return 1; ...
- idea 中pom.xml依赖版本号报错(报红,如下图所示)
1.maven工程中出现的错误 2.解决办法:file->setting->Maven 如果还没好的话请尝试以下方法:
- COMMIT - 提交当前事务
SYNOPSIS COMMIT [ WORK | TRANSACTION ] DESCRIPTION 描述 COMMIT 提交当前事务. 所有事务的更改都将为其他事务可见,而且保证当崩溃发生时的可持续 ...
- caffe这个c++工程的目录结构
目录结构 caffe文件夹下主要文件: data 用于存放下载的训练数据 docs 帮助文档 example 一些代码样例 matlab MATLAB接口文件 python Python接口文件 mo ...
- 借助百度地图API制作企业百度地图
做网站需要插入地图,可以借助百度地图API,具体步骤如下: 1.打开百度地图API的网址: http://api.map.baidu.com/lbsapi/creatmap/ 2.设置中心点 3. ...
- JFinal怎么更改项目服务的端口
如图所示,运行时启动的端口是80,现在将它改成801: 可以在Debug configuration 或 Run configuration 弹出的窗口中配置,方法右击项目>properties ...
- Java 调用存储过程 返回结果集
这里使用Oracle数据库的thin连接. 下面是存储过程SQL 1 createorreplaceprocedure proc3(stid in student.stuid%type, stname ...
- run loop
Objective-C之run loop详解 作者:wangzz 原文地址:http://blog.csdn.net/wzzvictory/article/details/9237973 转载请注明出 ...
- JS如何禁用浏览器的退格键
<script type="text/javascript"> //处理键盘事件 禁止后退键(Backspace)密码或单行.多行文本框除外 function forb ...