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. MySql(一)mysql服务的基本操作及环境配置

    MySQL服务的启动开始–>计算机–>右键选择管理–>双击打开服务和应用程序–>双击服务–>找到MySQL的服务名称(我的是MySQL56),右键选择启动即可 通过命令行 ...

  2. Jmeter之https请求

    Jmeter之录制https脚本,网上介绍了好多种方法,大家自行百度. 如果手写https脚本,该如何做呢? 方法:http信息头管理器,加入User-Agent参数 案例:手写百度的搜索:哈哈  请 ...

  3. cal - 显示一个日历

    总览 cal [-mjy ] [月份 [年份 ] ] 描述 Cal 显示一个简单的日历.. 如果没有指定参数, 则显示当前月份. 选项如下所列: -m 显示星期一作为一周的第一天.. (缺省为星期日. ...

  4. element-UI el-table二次封装

    Part.1 为什么要二次封装? 这是 Element 网站的 table 示例: <template> <el-table :data="tableData" ...

  5. 2.10.4 aside元素

    aside元素 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> < ...

  6. python send email

    #!/usr/bin/python # -*- coding: UTF-8 -*- # coding:utf8 from smtplib import SMTP_SSL from email.head ...

  7. [实现] 利用 Seq2Seq 预测句子后续字词 (Pytorch)

    最近有个任务:利用 RNN 进行句子补全,即给定一个不完整的句子,预测其后续的字词.本文使用了 Seq2Seq 模型,输入为5个中文字词,输出为一个中文字词. 目录 关于RNN 语料预处理 搭建数据集 ...

  8. svn in xcode5

    两种办法,一是使用比较成熟的svn客户端,二是使用终端.以下为终端方法: 假设已经通过Xcode->Preferences->Accounts将repository: http://mys ...

  9. 动态规划----最长公共子序列(C++实现)

    最长公共子序列 题目描述:给定两个字符串s1 s2 … sn和t1 t2 … tm .求出这两个字符串的最长公共子序列的长度.字符串s1 s2 … sn的子序列指可以表示为 … { i1 < i ...

  10. LCS以及输出路径模板

    记忆 两个for用来寻找LCS,DP是二维的,每一维代表了字符串的长度. 寻找的代码部分 if(a[i-1]==b[j-1]) dp[i][j]=dp[i-1][j-1]+1; else dp[i][ ...