Home > Web Front-end > Vue.js > Let's talk about the implementation principles of Provide and Inject in Vue3

Let's talk about the implementation principles of Provide and Inject in Vue3

青灯夜游
Release: 2022-02-16 20:09:59
forward
2991 people have browsed it

This article will give you an in-depth understanding of Vue3 and introduce the implementation principle of Provide / Inject in detail. I hope it will be helpful to everyone!

Let's talk about the implementation principles of Provide and Inject in Vue3

The implementation principle of Vue3's Provide/Inject is actually realized by clever use of prototypes and prototype chains, so before understanding the implementation principle of Vue3's Provide/Inject, we First review the knowledge of prototypes and prototype chains. [Related recommendations: vue.js video tutorial]

Knowledge review of prototype and prototype chain

    ##prototype and
  • __proto__
prototype is generally called the explicit prototype,

__proto__ is generally called the implicit prototype. After each function is created, by default, it will have a property named prototype, which represents the prototype object of the function.

    Prototype chain
When we access the properties of a JS object, JS will first search in the properties defined by the object. If it cannot find it, it will follow this The object's

__proto__ The chain associated with this implicit prototype searches for the previous object. This chain is called the prototype chain.

function Fn() {}
Fn.prototype.name = 'coboy'
let fn1 = new Fn()
fn1.age = 18
console.log(fn1.name) // coboy
console.log(fn1.age) // 18
Copy after login

fn1 is the instance object created by the Fn function new, fn1.age is the attribute on this instance object, and fn1.name comes from the Fn.prototype prototype object, because fn1’s

__proto__ The implicit prototype is the prototype object Fn.prototype pointing to the function Fn. A prototype chain allows one reference type to inherit the properties and methods of another reference type.

function Fn() {}
Fn.prototype.name = 'coboy'
let fn1 = new Fn()
fn1.name = 'cobyte'
console.log(fn1.name) // cobyte
Copy after login

When accessing the attribute name of the instance object fn1, JS will first search in the attributes of the instance object fn1. It happens that fn1 defines a name attribute, so it directly returns the value cobyte of its own attribute. Otherwise, it will continue to look up Fn.prototype along the prototype chain, and then it will return to coboy.

After reviewing the knowledge of prototypes and prototype chains, we began to explore the implementation principles of Provide/Inject.

Using Provide

When using

provide in setup(), we first start with vue Explicitly import the provide method. This allows us to call provide to define each property.

provide The function allows you to define a property through two parameters

    ##name (
  • type)

  • value
  • import { provide } from 'vue'
    
    export default {
      setup() {
        provide('name', 'coboy')
      }
    }
    Copy after login
provide API implementation principle

So what is the provide API implementation principle?

The provide function can be simplified to

export function provide(key, value) {
    // 获取当前组件实例
    const currentInstance: any = getCurrentInstance()
    if(currentInstance) {
        // 获取当前组件实例上provides属性
        let { provides } = currentInstance
        // 获取当前父级组件的provides属性
        const parentProvides = currentInstance.parent.provides
        // 如果当前的provides和父级的provides相同则说明还没赋值
        if(provides === parentProvides) {
            // Object.create() es6创建对象的另一种方式,可以理解为继承一个对象, 添加的属性是在原型下。
            provides = currentInstance.provides = Object.create(parentProvides)
        }
        provides[key] = value
    }
}
Copy after login

In summary, the provide API is to obtain the instance object of the current component and store the incoming data in the provides on the current component instance object. And through ES6's new API Object.create, the provides attribute of the parent component is set to the prototype object of the provides attribute of the current component instance object.

Processing of the provides attribute when the component instance object is initialized

Source code location: runtime-core/src/component.ts

Lets talk about the implementation principles of Provide and Inject in Vue3 By looking at the source code of the instance object, we can see that there are two attributes, parent and provides, on the instance component instance object. During initialization, if a parent component exists, assign the parent component's provides to the current component instance object's provides. If not, create a new object, and set the application context's provides attribute to the attribute on the prototype object of the new object. .

Using Inject

When using

inject

in setup(), you also need to start from vue Explicit import. After importing, we can call it to define the component mode exposed to us.

inject

The function has two parameters:

    The name of the property to be injected
  • Default Value (
  • optional

    )

    import { inject } from 'vue'
    
    export default {
      setup() {
        const name = inject('name', 'cobyte')
        return {
          name
        }
      }
    }
    Copy after login
inject API implementation principle

So what is the implementation principle of this inject API?

inject function can be simplified to

export function inject(
  key,
  defaultValue,
  treatDefaultAsFactory = false
) {
  // 获取当前组件实例对象
  const instance = currentInstance || currentRenderingInstance
  if (instance) {
    // 如果intance位于根目录下,则返回到appContext的provides,否则就返回父组件的provides
    const provides =
      instance.parent == null
        ? instance.vnode.appContext && instance.vnode.appContext.provides
        : instance.parent.provides

    if (provides && key in provides) {
      return provides[key]
    } else if (arguments.length > 1) {
      // 如果存在1个参数以上
      return treatDefaultAsFactory && isFunction(defaultValue)
        // 如果默认内容是个函数的,就执行并且通过call方法把组件实例的代理对象绑定到该函数的this上
        ? defaultValue.call(instance.proxy) 
        : defaultValue
    }
  }
}
Copy after login

Through inject source code analysis, we can know that inject first obtains the instance object of the current component, and then determines whether it is the root component. If it is the root component, it returns to the appContext Provides, otherwise the provides of the parent component are returned.

If the currently obtained key has a value on provides, then return the value. If not, determine whether there is default content. If the default content is a function, execute it and use the call method to set the proxy object of the component instance. Bind to this function, otherwise the default content will be returned directly.

provide/inject实现原理总结

通过上面的分析,可以得知provide/inject实现原理还是比较简单的,就是巧妙地利用了原型和原型链进行数据的继承和获取。provide API调用设置的时候,设置父级的provides为当前provides对象原型对象上的属性,在inject获取provides对象中的属性值时,优先获取provides对象自身的属性,如果自身查找不到,则沿着原型链向上一个对象中去查找。

拓展:Object.create原理

方法说明

  • Object.create()方法创建一个新的对象,并以方法的第一个参数作为新对象的__proto__属性的值(以第一个参数作为新对象的构造函数的原型对象)
  • Object.create()方法还有第二个可选参数,是一个对象,对象的每个属性都会作为新对象的自身属性,对象的属性值以descriptor(Object.getOwnPropertyDescriptor(obj, 'key'))的形式出现,且enumerable默认为false

源码模拟

Object.myCreate = function (proto, propertyObject = undefined) {
    if (propertyObject === null) {
        // 这里没有判断propertyObject是否是原始包装对象
        throw 'TypeError'
    } else {
        function Fn () {}
        // 设置原型对象属性
        Fn.prototype = proto
        const obj = new Fn()
        if (propertyObject !== undefined) {
            Object.defineProperties(obj, propertyObject)
        }
        if (proto === null) {
            // 创建一个没有原型对象的对象,Object.create(null)
            obj.__proto__ = null
        }
        return obj
    }
}
Copy after login

定义一个空的构造函数,然后指定构造函数的原型对象,通过new运算符创建一个空对象,如果发现传递了第二个参数,通过Object.defineProperties为创建的对象设置key、value,最后返回创建的对象即可。

示例

// 第二个参数为null时,抛出TypeError
// const throwErr = Object.myCreate({name: 'coboy'}, null)  // Uncaught TypeError
// 构建一个以
const obj1 = Object.myCreate({name: 'coboy'})
console.log(obj1)  // {}, obj1的构造函数的原型对象是{name: 'coboy'}
const obj2 = Object.myCreate({name: 'coboy'}, {
    age: {
        value: 18,
        enumerable: true
    }
})
console.log(obj2)  // {age: 18}, obj2的构造函数的原型对象是{name: 'coboy'}
Copy after login

拓展:两个连续赋值的表达式

provides = currentInstance.provides = Object.create(parentProvides) 发生了什么?

Object.create(parentProvides) 创建了一个新的对象引用,如果只是把 currentInstance.provides 更新为新的对象引用,那么provides的引用还是旧的引用,所以需要同时把provides的引用也更新为新的对象引用。

来自《JavaScript权威指南》的解析

  • JavaScript总是严格按照从左至右的顺序来计算表达式
  • 一切都是表达式,一切都是运算
provides = currentInstance.provides = Object.create(parentProvides)
Copy after login

上述的provides是一个表达式,它被严格地称为“赋值表达式的左手端(Ihs)操作数”。 而右侧 currentInstance.provides = Object.create(parentProvides) 这一个整体也当做一个表达式,这一个整体赋值表达式的计算结果是赋值给了最左侧的providescurrentInstance.provides = Object.create(parentProvides) 这个表达式同时也是一个赋值表达式,Object.create(parentProvides)创建了一个新的引用赋值给了currentInstance这个引用上的provides属性

currentInstance.provides这个表达式的语义是:

  • 计算单值表达式currentInstance,得到currentInstance的引用
  • 将右侧的名字provides理解为一个标识符,并作为“.”运算的右操作数
  • 计算currentInstance.provides表达式的结果(Result)

currentInstance.provides当它作为赋值表达式的左操作数时,它是一个被赋值的引用,而当它作为右操作数时,则计算它的值。

注意:赋值表达式左侧的操作数可以是另一个表达式,而在声明语句中的等号左边,绝不可能是一个表达式。 例如上面的如果写成了let provides = xxx,那么这个时候,provides只是一个表达名字的、静态语法分析期作为标识符来理解的字面文本,而不是一个表达式

(学习视频分享:web前端教程

The above is the detailed content of Let's talk about the implementation principles of Provide and Inject in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template