normalize-children.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /* @flow */
  2. import { isPrimitive } from 'core/util/index'
  3. import VNode, { createTextVNode } from 'core/vdom/vnode'
  4. export function normalizeChildren (children: any): ?Array<VNode> {
  5. return isPrimitive(children)
  6. ? [createTextVNode(children)]
  7. : Array.isArray(children)
  8. ? normalizeArrayChildren(children)
  9. : undefined
  10. }
  11. function normalizeArrayChildren (children: any, nestedIndex?: string): Array<VNode> {
  12. const res = []
  13. let i, c, last
  14. for (i = 0; i < children.length; i++) {
  15. c = children[i]
  16. if (c == null || typeof c === 'boolean') continue
  17. last = res[res.length - 1]
  18. // nested
  19. if (Array.isArray(c)) {
  20. res.push.apply(res, normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`))
  21. } else if (isPrimitive(c)) {
  22. if (last && last.text) {
  23. last.text += String(c)
  24. } else if (c !== '') {
  25. // convert primitive to vnode
  26. res.push(createTextVNode(c))
  27. }
  28. } else {
  29. if (c.text && last && last.text) {
  30. res[res.length - 1] = createTextVNode(last.text + c.text)
  31. } else {
  32. // default key for nested array children (likely generated by v-for)
  33. if (c.tag && c.key == null && nestedIndex != null) {
  34. c.key = `__vlist${nestedIndex}_${i}__`
  35. }
  36. res.push(c)
  37. }
  38. }
  39. }
  40. return res
  41. }