• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[VueJS+Typescript]DecoupleDependenciesUsingIoCContainersinVuewithTypeScriptandIn ...

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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>

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript-类与接口发布时间:2022-07-18
下一篇:
TypeScript-类型声明、枚举、函数、接口发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap