vText.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import {
  2. type DirectiveTransform,
  3. TO_DISPLAY_STRING,
  4. createCallExpression,
  5. createObjectProperty,
  6. createSimpleExpression,
  7. getConstantType,
  8. } from '@vue/compiler-core'
  9. import { DOMErrorCodes, createDOMCompilerError } from '../errors'
  10. export const transformVText: DirectiveTransform = (dir, node, context) => {
  11. const { exp, loc } = dir
  12. if (!exp) {
  13. context.onError(
  14. createDOMCompilerError(DOMErrorCodes.X_V_TEXT_NO_EXPRESSION, loc),
  15. )
  16. }
  17. if (node.children.length) {
  18. context.onError(
  19. createDOMCompilerError(DOMErrorCodes.X_V_TEXT_WITH_CHILDREN, loc),
  20. )
  21. node.children.length = 0
  22. }
  23. return {
  24. props: [
  25. createObjectProperty(
  26. createSimpleExpression(`textContent`, true),
  27. exp
  28. ? getConstantType(exp, context) > 0
  29. ? exp
  30. : createCallExpression(
  31. context.helperString(TO_DISPLAY_STRING),
  32. [exp],
  33. loc,
  34. )
  35. : createSimpleExpression('', true),
  36. ),
  37. ],
  38. }
  39. }