diff --git a/packages/core/src/platform/builtInMixins/relationsMixin.js b/packages/core/src/platform/builtInMixins/relationsMixin.js index 15c8c59605..3d30eadefb 100644 --- a/packages/core/src/platform/builtInMixins/relationsMixin.js +++ b/packages/core/src/platform/builtInMixins/relationsMixin.js @@ -1,5 +1,5 @@ import { isObject } from '@mpxjs/utils' -import { CREATED, MOUNTED, BEFOREUNMOUNT } from '../../core/innerLifecycle' +import { BEFORECREATE, MOUNTED, BEFOREUNMOUNT } from '../../core/innerLifecycle' const targets = [] let curTarget = null @@ -177,8 +177,9 @@ export default function relationsMixin (mixinType) { } } else if (__mpx_mode__ === 'web' && mixinType === 'component') { return { - [CREATED] () { + [BEFORECREATE] () { this.__mpxRelations = {} + this.__mpxRelationNodesMap = {} // 用于getRelationNodes关系查询 }, [MOUNTED] () { this.__mpxCollectRelations() @@ -186,8 +187,14 @@ export default function relationsMixin (mixinType) { }, [BEFOREUNMOUNT] () { this.__mpxExecRelations('unlinked') + // 重置缓存数据 + this.__mpxRelations = {} + this.__mpxRelationNodesMap = {} }, methods: { + getRelationNodes (path) { + return this.__mpxRelationNodesMap[path] || null + }, __mpxCollectRelations () { const relations = this.__mpxProxy.options.relations if (!relations) return @@ -221,6 +228,7 @@ export default function relationsMixin (mixinType) { targetRelation, relation } + this.__mpxRelationNodesMap[path] = [target] // 子级绑定父级 } else if (type === 'ancestor') { // 当前匹配失败,但type为ancestor时,继续向上查找 return this.__mpxCheckParent(target, relation, path) @@ -230,6 +238,12 @@ export default function relationsMixin (mixinType) { __mpxExecRelations (type) { Object.keys(this.__mpxRelations).forEach(path => { const { target, targetRelation, relation } = this.__mpxRelations[path] + const currentPath = this.$options.componentPath + if (type === 'linked') { + this.__mpxLinkRelationNodes(target, currentPath) + } else if (type === 'unlinked') { + this.__mpxRemoveRelationNodes(target, currentPath) + } if (typeof targetRelation[type] === 'function') { targetRelation[type].call(target, this) } @@ -237,6 +251,15 @@ export default function relationsMixin (mixinType) { relation[type].call(this, target) } }) + }, + __mpxLinkRelationNodes (target, path) { + target.__mpxRelationNodesMap[path] = target.__mpxRelationNodesMap[path] || [] // 父级绑定子级 + target.__mpxRelationNodesMap[path].push(this) + }, + __mpxRemoveRelationNodes (target, path) { + const arr = target.__mpxRelationNodesMap[path] || [] + const index = arr.indexOf(this) + if (index !== -1) arr.splice(index, 1) } } }