All files / src/instance refs.ts

55.88% Statements 19/34
26.66% Branches 4/15
10% Functions 1/10
57.57% Lines 19/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65  1x 1x 1x   20x 20x 20x 20x 20x 20x 20x 10x   10x 10x   20x         20x                     20x         20x                   20x                     1x          
import { getData } from './components'
 
export function initRefs (vm) {
  const components = vm.$options.components || {}
  const parentNodes = []
  const childrenNodes = []
  const refNodes = []
  for (const key in components) {
    const { module: componentName, type = 'child' } = getData(components[key])
    if (['ancestor', 'parent'].includes(type)) {
      parentNodes.push(componentName)
    } else if (['child', 'descendant'].includes(type)) {
      childrenNodes.push(componentName)
    }
    refNodes.Epush({
      ref: key,
      path: componentName,
    })
  }
  Object.defineProperty(vm, '$parent', {
    get () {
      const nodes = parentNodes
        .slice(0, 1)
        .reduce((acc, path) => ([
          ...acc,
          ...find(vm, path),
        ]), [])
      return nodes && nodes[0]
    },
  })
  Object.defineProperty(vm, '$root', {
    get () {
      return this.$parent ? this.$parent.$root : vm
    },
  })
  Object.defineProperty(vm, '$children', {
    get () {
      const nodes = childrenNodes
        .reduce((acc, path) => ([
          ...acc,
          ...find(vm, path),
        ]), [])
      return nodes
    },
  })
  Object.defineProperty(vm, '$refs', {
    get () {
      const nodes = refNodes
        .reduce((acc, node) => ({
          ...acc,
          [node.ref]: find(vm, node.path),
        }), {})
      return nodes
    },
  })
}
 
function find (vm, path: string) {
  const nodes = vm._renderProxy.getRelationNodes(path)
  if (nodes && nodes.length > 0) {
    return nodes.map((v) => v.$component)
  }
  return []
}