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的更多相关文章

  1. IoC Containers with Xamarin

    When writing cross platform apps with Xamarin, our goal is share as close to 100% of our code across ...

  2. vue与TypeScript集成配置最简教程

    https://blog.csdn.net/u014633852/article/details/73706459 https://segmentfault.com/a/119000001187808 ...

  3. Vue Cli3 TypeScript 搭建工程

    Vue Cli3出来也一段时间了,我想尝试下Vue结合TypeScript搭建个工程,感受下Vue下用TS...网上有一篇讲的非常详细的教程  vue-cli3.0 搭建项目模版教程(ts+vuex+ ...

  4. MVVMLight - IOC Containers and MVVM

    在面向对象编程的早期,开发者要面对在应用程序或者类库中创建或检索类的实例的问题.针对这个问题有很多的解决方案.在过去几年中,依赖注入(DI)和控制反转(IoC)在开发者中很流行,并且取代了老的方案,比 ...

  5. 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 ...

  6. Vue + WebPack + Typescript初学者VSCode项目 (按需加载、跨域调试、await/async)

    万事开头难,一个好的Hello World程序可以节省我们好多的学习时间,帮助我们快速入门.Hello World程序之所以是入门必读必会,就是因为其代码量少,简单易懂.但我觉得,还应该做到功能丰富, ...

  7. [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 ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. 使用cmd查看Tensorboard的生成图

    代码中"graph_practice7/"文件存放的是生成的神经网络图 现在要查看这个图,使用cmd 进入文件指定目录(我的文件存储地址是E:\workspace\PycharmP ...

  2. 用npm来部署快速一个httpweb服务器

    https://blog.csdn.net/u012182627/article/details/55060594 http-server的安装######注意事项 安装http-server的时候 ...

  3. freenas iscsi initiator 配置

    1.加载Iscsi Initiator 模块 freebsd从7.0开始已经包含了Iscsi Initiator ,不需要安装后再使用,但在使用前,需要加载模块. # kldload -v iscsi ...

  4. 流行-Manifold【0】-维基百科中文版本解释

  5. 新引入thinkphp报错“应用目录[./Application/]不可写,目录无法自动生成! 请手动生成项目目录~”

    新引入thinkphp报错“应用目录[./Application/]不可写,目录无法自动生成! 请手动生成项目目录~”, 其主要原因是文件夹的权限问题,手动将项目文件夹权限更改为可读可写就OK,具体操 ...

  6. nodejs学习(二) ---- express中使用模板引擎jade

    系列教程,上一节教程  express+nodejs快速创建一个项目 在创建一个项目后,views目录下的文件后缀为 .jade . 打开 index.jade,具体内容如下图(忽略 header.j ...

  7. Reparameterization Trick

    目录 Sample() is not differentiable Reparameterization trick Too Complex Sample() is not differentiabl ...

  8. Java线上应用故障排查

    线上故障主要2种: CPU利用率很高, 内存占用率很大 一.CPU利用率很高 1. top查询那个进程CPU使用率高 2. 显示进程列表 ps -mp pid -o THREAD,tid,time 找 ...

  9. 洛谷 4933 洛谷10月月赛II T2 大师

    [题解] f[i][j]表示最后一个数为h[i],公差为j的等差数列的个数.n方枚举最后一个数和倒数第二个数转移即可.注意公差可能为负数,需要移动为正数再作为下标. #include<cstdi ...

  10. Uva 12657 移动盒子(双向链表)

    题意: 你有一行盒子,从左到右依次编号为1, 2, 3,…, n.可以执行以下4种指令:1 X Y表示把盒子X移动到盒子Y左边(如果X已经在Y的左边则忽略此指令).2 X Y表示把盒子X移动到盒子Y右 ...