Let's start DI in Vue3

Introduction

Vue3 has a dependency injection system to deliver props to the nesting component. This article introduces it and personal opinion.

What is DI

In software engineering, dependency injection is a technique in which an object receives other objects that it depends on, called dependencies.

I quoted it from Wikipedia.

Roughly to say, When class A uses class B function or variable, class A has a dependency, Class A should have class B as a member variable.

It helps us to reduce dependency, So we can test it easily.

However, Vue3 DI is slightly different from the original DI definition. its role is similar to store.

How to use

There are 3 step

step1: generate key

// keyStore.ts
export const key = Symbol('testKey');

step2: register key and value

//parent.vue
import {provide} from "vue";
import {key} from "@/keyStore"
provide(key, "test");

step3: get value

// child.vue
import {inject} from "vue";
import {key} from "@/keyStore"

const value = inject(key)
console.log(value) // "test"

If you register the key as a static value, the type will unknown. So, I recommend you use symbol key as much as you can. e.x

//parent.vue
import {provide} from "vue";
provide("test", "test");
// child.vue
import {inject} from "vue";
import {key} from "@/keyStore"

const value = inject(key) // value's type is unkown
console.log(value)

Diffrence between DI and Vuex

Vuex

pros

  • Data flow is fixed.
  • debugging and testing tools are plenty.

cons

  • The store is global
  • If your application is small, the benefit is little.

DI

pros

  • It can create a store that is limited access.
  • It can create a store without another package.

cons

  • We have to design data flow, So management costs will grow.
  • If your application is big, management costs will grow.

    finally

    I hope this article will help you.