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!
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]
__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.
__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
__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
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
type)
import { provide } from 'vue' export default { setup() { provide('name', 'coboy') } }
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 } }
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 initializedBy 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 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.
The function has two parameters:
)
import { inject } from 'vue' export default { setup() { const name = inject('name', 'cobyte') return { name } } }
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 } } }
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 API调用设置的时候,设置父级的provides为当前provides对象原型对象上的属性,在inject获取provides对象中的属性值时,优先获取provides对象自身的属性,如果自身查找不到,则沿着原型链向上一个对象中去查找。
方法说明
__proto__
属性的值(以第一个参数作为新对象的构造函数的原型对象)源码模拟
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 } }
定义一个空的构造函数,然后指定构造函数的原型对象,通过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'}
provides = currentInstance.provides = Object.create(parentProvides)
发生了什么?
Object.create(parentProvides)
创建了一个新的对象引用,如果只是把 currentInstance.provides
更新为新的对象引用,那么provides
的引用还是旧的引用,所以需要同时把provides
的引用也更新为新的对象引用。
来自《JavaScript权威指南》的解析
provides = currentInstance.provides = Object.create(parentProvides)
上述的provides是一个表达式,它被严格地称为“赋值表达式的左手端(Ihs)操作数”。
而右侧 currentInstance.provides = Object.create(parentProvides)
这一个整体也当做一个表达式,这一个整体赋值表达式的计算结果是赋值给了最左侧的providescurrentInstance.provides = Object.create(parentProvides)
这个表达式同时也是一个赋值表达式,Object.create(parentProvides)创建了一个新的引用赋值给了currentInstance这个引用上的provides属性
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!