69d8c620d773c92ea3c0e6bd1ea6313b448734d93d22d830b8bc5d9ac87af818b9de726e8cccdb1ff86e0fcb92a3a277603fa63644c7649c669d91892da8a0 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* @flow */
  2. import { addIfCondition } from 'compiler/parser/index'
  3. import { getAndRemoveAttr, addRawAttr } from 'compiler/helpers'
  4. function hasConditionDirective (el: ASTElement): boolean {
  5. for (const attr in el.attrsMap) {
  6. if (/^v\-if|v\-else|v\-else\-if$/.test(attr)) {
  7. return true
  8. }
  9. }
  10. return false
  11. }
  12. function getPreviousConditions (el: ASTElement): Array<string> {
  13. const conditions = []
  14. if (el.parent && el.parent.children) {
  15. for (let c = 0, n = el.parent.children.length; c < n; ++c) {
  16. // $flow-disable-line
  17. const ifConditions = el.parent.children[c].ifConditions
  18. if (ifConditions) {
  19. for (let i = 0, l = ifConditions.length; i < l; ++i) {
  20. const condition = ifConditions[i]
  21. if (condition && condition.exp) {
  22. conditions.push(condition.exp)
  23. }
  24. }
  25. }
  26. }
  27. }
  28. return conditions
  29. }
  30. export function preTransformVIf (el: ASTElement, options: WeexCompilerOptions) {
  31. if (hasConditionDirective(el)) {
  32. let exp
  33. const ifExp = getAndRemoveAttr(el, 'v-if', true /* remove from attrsMap */)
  34. const elseifExp = getAndRemoveAttr(el, 'v-else-if', true)
  35. // don't need the value, but remove it to avoid being generated as a
  36. // custom directive
  37. getAndRemoveAttr(el, 'v-else', true)
  38. if (ifExp) {
  39. exp = ifExp
  40. addIfCondition(el, { exp: ifExp, block: el })
  41. } else {
  42. elseifExp && addIfCondition(el, { exp: elseifExp, block: el })
  43. const prevConditions = getPreviousConditions(el)
  44. if (prevConditions.length) {
  45. const prevMatch = prevConditions.join(' || ')
  46. exp = elseifExp
  47. ? `!(${prevMatch}) && (${elseifExp})` // v-else-if
  48. : `!(${prevMatch})` // v-else
  49. } else if (process.env.NODE_ENV !== 'production' && options.warn) {
  50. options.warn(
  51. `v-${elseifExp ? ('else-if="' + elseifExp + '"') : 'else'} ` +
  52. `used on element <${el.tag}> without corresponding v-if.`
  53. )
  54. return
  55. }
  56. }
  57. addRawAttr(el, '[[match]]', exp)
  58. }
  59. }