[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 ...
随机推荐
- 迅为双核imx6DL核心板_ARM定制专家_Cortex SATA 千兆网 4G GPS
核心板参数 尺寸:51mm*61mm CPU:Freescale Cortex-A9 双核精简版 i.MX6DL,主频 1.2 GHz 内存:1GB DDR3 存储:8GB EMMC 存储 EEPRO ...
- 【转】自动识别是手机端还是pc端只用一行代码就搞定
<script type="text/javascript"> var mobileAgent = new Array("iphone", &quo ...
- 5-Java-C(单位分数)
题目描述: 形如:1/a 的分数称为单位分数. 可以把1分解为若干个互不相同的单位分数之和. 例如: 1 = 1/2 + 1/3 + 1/9 + 1/18 1 = 1/2 + 1/3 + 1/10 + ...
- 00C#
C# C#(读作“See Sharp”)是一种简单.现代.面向对象且类型安全的编程语言.C# 起源于 C 语言家族,因此,对于 C.C++ 和 Java 程序员,可以很快熟悉这种新的语言.C# 已经分 ...
- 01Oracle Database
Oracle Database Oracle Database又名Oracle RDBMS简称Oracle是甲骨文公司的一款关系数据库管理系统. Oracle Website.
- ffmpeg裁剪
http://it6655.com/2012/09/ffmpeg-9-2-html 1 configure参数 1 通用选项 在linux下进入终端,找到ffmpeg解压位置,输入如下命令: root ...
- js 页面图片等元素在普通元素中滚动动态加载技术
/*! * 2012-01-13 v1.1 偏移值计算修改 position → offset * 2012-09-25 v1.2 增加滚动容器参数, 回调参数 * 2015-11-17 v1.3 只 ...
- python 3 廖雪峰博客笔记(一) python特性
python 是一种解释性语言,代码在执行时会一行一行翻译成CPU能理解的机器语言. python 的特点是简单优雅. python 的优点是 代码优雅 基础代码库丰富,包括网络.文件.GUI.数据库 ...
- 2018湖南省第14届大学生计算机程序设计竞赛 D: 卖萌表情
Description 已知以下 4 种都是卖萌表情(空白的部分可以是任意字符.竖线是便于展示的分隔符,没有实际意义): ^ ^ | ^ | < | > v | v v | > | ...
- Centos6.8 安装mongo3.6以及权限配置和开启外网链接
目录 安装环境和版本说明,以及参考文档链接 安装MongoDB数据库 运行MongoDB数据库 删除卸载MongoDB 配置MongoDB管理员用户 修改配置文件,允许外网链接 安装配置完成,使用Ro ...