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

Examples of MySQL and Python interaction

Table of contents 1. Prepare data Create a data t...

Analysis of the principles and usage of Docker container data volumes

What is a container data volume If the data is in...

Vue3 encapsulates its own paging component

This article example shares the specific code of ...

How to create a my.ini file in the MySQL 5.7.19 installation directory

In the previous article, I introduced the detaile...

WebStorm cannot correctly identify the solution of Vue3 combined API

1 Problem Description Vue3's combined API can...

Gradient slide effect implemented by CSS3

Achieve results Code html <div class="css...

Summary of web designers' experience and skills in learning web design

As the company's influence grows and its prod...

Even a novice can understand the difference between typeof and instanceof in js

Table of contents 1. typeof 2. instanceof 3. Diff...

Comprehensive summary of mysql functions

Table of contents 1. Commonly used string functio...

Detailed tutorial on installing Python 3.6.6 from scratch on CentOS 7.5

ps: The environment is as the title Install possi...

Some tips on using the HTML title attribute correctly

If you want to hide content from users of phones, ...

Element table header row height problem solution

Table of contents Preface 1. Cause of the problem...

Detailed steps for using jib for docker deployment in Spring Cloud

Introduction to Jib Jib is a library developed by...

Examples of using the ES6 spread operator

Table of contents What are spread and rest operat...