Dependency Injection In Vue
Dependency injection (DI), is an important application design pattern. Here provide DI framework for
Vue
, which is typically used in the design of Vue applications to increase their efficiency and modularity. Dependencies are services or objects that a class needs to perform its function. DI is a coding pattern in which a class asks for dependencies from external sources rather than creating them itself. In Vue, this library DI framework provides declared dependencies to a class when that class is instantiated. you can use it to make your apps flexible, efficient, and robust, as well as testable and maintainable.
Get Started
-
Install package
yarn add vue-ioc-di
-
Create a service
app.service.ts
;// global service -
Use in vue component
<template><div>{{ srv.name }}<game></game></div></template><script lang="ts">import Vue from 'vue';import { Component } from 'vue-property-decorator';import Game from './components/game/index.vue';import { AppService } from './app.service';import { Reactive, Injectable, Inject } from 'vue-ioc-di';@Component({components: {Game},providers: [ AppService ], // When `AppService` provide in 'root', omit it.})export default class App extends Vue {@Inject(AppService)srv!: AppService;doWork() {// use servicethis.srv.doSomething();}}</script><style scoped></style> -
More about Dependency injection.