Analyze the usage and principles of Vue's provide and inject

Analyze the usage and principles of Vue's provide and inject

First, let's talk about why we use provide/inject? For communication between grandfather and grandson components, or even between great-grandfather components and grandson components, we can just use vuex.

That is indeed the case, but please listen to me, sometimes your project is relatively small and there are even few scenarios for component communication. In that case, isn’t it a waste to introduce vuex just for a few communication parameters? Some people may also think of using $parent to get the parent component instance to get data/methods. This is fine for two layers, but what about multiple layers? If the components are deeply nested, how do you do it? Write a function to encapsulate $parent again. Wouldn’t that be very troublesome? You don’t have to take a roundabout way to solve the problem when it’s already there. Haha~that’s going off topic.

Without further ado, I will just tell you that using provide/inject is the solution to your problems. Let’s see how to use it? Backhand is just a few lines of simple code:

1. The parent component provides the parameters to be passed to the child component provide() {
    return {
      listType: this.listType,
    }
  }
2. Subcomponent usage:
inject: ['listType'],

Of course, you can also specify your default values ​​and the source of your parameters in inject:

inject:{
  listType:{
  from:"par"//provide the defined name default:1
  }
}

Okay! Isn’t it simple? In fact, both parent components and ancestor components can inject dependencies into descendant components, no matter how deep the component hierarchy is.

Some more:

provide can be an object or a function that returns an object.

inejct: can be a string array or an object.

If you are interested, take a look at the source code below, which is also quite easy to understand:

Provide the core source code:

export function provide<T>(key: InjectionKey<T> | string | number, value: T) {
  if (!currentInstance) {
    if (__DEV__) {
      warn(`provide() can only be used inside setup().`)
    
    }
  } else {
    //Get the provides of the current component. The default instance inherits the provides object of the parent class. let provides = currentInstance.provides
    //Use the parent provided object as a prototype to create your own provided object const parentProvides =
      currentInstance.parent && currentInstance.parent.provides
    if (parentProvides === provides) {
      provides = currentInstance.provides = Object.create(parentProvides)
    }
    provides[key as string] = value
  }
}
​

Inject's core source code:

export function inject(
  key: InjectionKey<any> | string,
  defaultValue?: unknown,
  treatDefaultAsFactory = false
) {
  //Get the current component instance const instance = currentInstance || currentRenderingInstance
  if (instance) {
  //Get provides
    const provides =
      instance.parent == null
        ? instance.vnode.appContext && instance.vnode.appContext.provides
        : instance.parent.provides
​
    if (provides && (key as string | symbol) in provides) {
      //If the key exists, return directly provides[key as string]
    } else if (arguments.length > 1) {
      //If the key does not exist, set the default value and return the default value directly return treatDefaultAsFactory && isFunction(defaultValue)
        ? defaultValue.call(instance.proxy)
        : defaultValue
    } else if (__DEV__) {
      //If none of them are found, warn(`injection "${String(key)}" not found.`)
    }
  } else if (__DEV__) {
    warn(`inject() can only be used inside setup() or functional components.`)
  }
}
​

This concludes this article on parsing the usage and principles of Vue's provide and inject. For more information on the usage of Vue provide and inject, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue solves the problem of provide and inject response
  • Example of how to implement responsive data update using provide/inject in Vue.js
  • How to use [provide/inject] in Vue to implement page reload
  • Practical application of provide/inject combination in Vue 2.0
  • Learning and using provide/inject in Vue

<<:  HTML Frameset Example Code

>>:  Example code for implementing a circular trajectory animation using CSS3 and table tags

Recommend

Several ways to add timestamps in MySQL tables

Scenario: The data in a table needs to be synchro...

CSS warped shadow implementation code

This article introduces the implementation code o...

CSS implements 0.5px lines to solve mobile compatibility issues (recommended)

【content】: 1. Use background-image gradient style...

Solve the compatibility issue between MySQL 8.0 driver and Alibaba Druid version

This article mainly introduces the solution to th...

Detailed explanation of MySQL 8.0 password expiration policy

Starting from MySQL 8.0.16, you can set a passwor...

MySQL master-slave configuration study notes

● I was planning to buy some cloud data to provid...

Detailed explanation of Docker usage under CentOS8

1. Installation of Docker under CentOS8 curl http...

jQuery plugin to implement minesweeper game (1)

This article shares the specific code of the firs...

HTML page adaptive width table

In the pages of WEB applications, tables are ofte...

A brief discussion on MySQL user permission table

MySQL will automatically create a database named ...

Vue project code splitting solution

Table of contents background Purpose Before split...

Several commonly used single-page application website sharing

CSS3Please Take a look at this website yourself, ...

MySQL GTID comprehensive summary

Table of contents 01 Introduction to GTID 02 How ...