[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 ...
随机推荐
- OpenCV3.3安装教程
http://blog.csdn.net/amusi1994/article/details/76768775?locationNum=10&fps=1
- HDU_1237_简单计算器
运算符为+,-,*,/:操作数为整数:且没有括号 设定符号优先级,先在栈底压运算符0 #include<iostream> #include<cstdio> #include& ...
- xcode 通配搜索
class \w*<\w*> extension \w*: \w* \{\} 搜索所有泛型类.
- nginx 服务器
1.windows版本的nginx启动报错 No mapping for the Unicode character exists in the target multi-byte code page ...
- flutter 实现圆角头像的2种方法
圆角头像在开发中应用太普遍了,我总结了2种实现方法,分享给大家 方法一: 使用Container组件的decoration可以实现 Container( width: 40, height: 40, ...
- Flutter web环境变量搭建及开发
使用flutter开发app已有三个月,有一些行为形成了惯性,在搭建flutter web环境变量时走了不少的坑,分享出来,免得其他小伙伴再走一遍. 首先flutter的版本要使用1.5及以上版本 d ...
- AUSU 安装Win10注意事项
Win10 U盘原版安装 安装前在电脑店PE里用DiskGenius分区分区表类型:GUID勾选:创建新ESP分区 . 创建MSR分区 安装必须使用UEFI引导和GPT硬盘,否则会提示无法安装Win1 ...
- Zend Studio / Eclipse 缩进设置
首先是Window – Preferences打开Preferences配置对话框: 然后依次找到PHP – Code Style – Formatter,如下图所示: 这里注意一下Active pr ...
- 服务器设置禁ping
//设置Linux服务器禁ping!!!终端命令行直接输入 echo 1 >/proc/sys/net/ipv4/icmp_echo_ignore_all 这个是关闭ping的命令. 如果你想要 ...
- EasyUI入门,DataGrid(数据表格)
搭建EasyUI 1.进入官网,下载EasyUI的程序包.地址:http://www.jeasyui.com/download/list.php 2.先导入css样式,引入程序包 3.进入EasyUI ...