|
楼主 |
发表于 2022-9-19 22:31:29
|
显示全部楼层
在整个Vue源码选项合并过程中, 区分子类, 还是根实例, 通过判断参数是否传递了 vm.
1. 在子类中,子类 data 不是一个函数, 发生报错的信息,返回父组件的 parentVal, 如果是一个函数 直接调用 mergeDataOrFn 函数, 进行数据合并,不传入 vm
2. vm 是根实例, 调用 mergeDataOrFn 函数, 并传入 vm
mergeDataOrFn函数的源码如下
- function mergeDataOrFn( parentVal, childVal,vm) {
- if (!vm) { /*子类*/
- // in a Vue.extend merge, both should be functions
- /* 通过 Vue.extend的子类, 父子的data都应该是一个函数*/
- if (!childVal) {
- return parentVal
- }
- if (!parentVal) {
- return childVal
- }
- /*childVal, parentVal都没有传递, 运行到此结束 */
- // when parentVal & childVal are both present,
- // we need to return a function that returns the
- // merged result of both functions... no need to
- // check if parentVal is a function here because
- // it has to be a function to pass previous merges.
- /*能够运行到这里, childVal,parentVal都会有值,才进行合并*/
- return function mergedDataFn() {
- /*将childVal,parentVal通过call来的调用, 把返回值纯对象当做参数传递给mergeData()函数*/
- return mergeData(
- typeof childVal === 'function' ? childVal.call(this, this) : childVal,
- typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal
- )
- }
- } else { /*vm根实例*/
- return function mergedInstanceDataFn() {
- // instance merge
- var instanceData = typeof childVal === 'function'
- ? childVal.call(vm, vm)
- : childVal;
- var defaultData = typeof parentVal === 'function'
- ? parentVal.call(vm, vm)
- : parentVal;
- if (instanceData) {
- return mergeData(instanceData, defaultData)
- } else {
- return defaultData
- }
- }
- }
- }
复制代码 |
|