[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>
复制代码

 

posted @   Zhentiw  阅读(1758)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-08-28 [D3] Creating a D3 Force Layout in React
2017-08-28 [D3] Animate Chart Axis Transitions in D3 v4
2015-08-28 [Javascript] Linting JavaScript with ESLint
2015-08-28 [CSS] Transition
点击右上角即可分享
微信分享提示