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

Mysql inner join on usage examples (must read)

Grammatical rules SELECT column_name(s) FROM tabl...

Detailed explanation of this pointing problem in JavaScript

Preface The this pointer in JS has always been a ...

Vue uses drag and drop to create a structure tree

This article example shares the specific code of ...

Markup validation for doctype

But recently I found that using this method will c...

Detailed steps to install web server using Apache httpd2.4.37 on centos8

Step 1: yum install httpd -y #Install httpd servi...

Solution to forgetting mysql database password

You may have set a MySQL password just now, but f...

A brief comparison of Props in React

Table of contents Props comparison of class compo...

The most complete package.json analysis

Table of contents 1. Overview 2. Name field 3. Ve...

How to use the Fuser command in Linux system

What is Fuser Command? The fuser command is a ver...

MySQL 5.7.18 free installation version window configuration method

This is my first blog. It’s about when I started ...

How to install docker on centos

Here we only introduce the relatively simple inst...

JavaScript implements an input box component

This article example shares the specific code for...