vBind.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { DirectiveTransform } from '../transform'
  2. import { createObjectProperty, createSimpleExpression, NodeTypes } from '../ast'
  3. import { createCompilerError, ErrorCodes } from '../errors'
  4. import { camelize } from '@vue/shared'
  5. import { CAMELIZE } from '../runtimeHelpers'
  6. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  7. // codegen for the entire props object. This transform here is only for v-bind
  8. // *with* args.
  9. export const transformBind: DirectiveTransform = (dir, _node, context) => {
  10. const { exp, modifiers, loc } = dir
  11. const arg = dir.arg!
  12. if (arg.type !== NodeTypes.SIMPLE_EXPRESSION) {
  13. arg.children.unshift(`(`)
  14. arg.children.push(`) || ""`)
  15. } else if (!arg.isStatic) {
  16. arg.content = `${arg.content} || ""`
  17. }
  18. // .prop is no longer necessary due to new patch behavior
  19. // .sync is replaced by v-model:arg
  20. if (modifiers.includes('camel')) {
  21. if (arg.type === NodeTypes.SIMPLE_EXPRESSION) {
  22. if (arg.isStatic) {
  23. arg.content = camelize(arg.content)
  24. } else {
  25. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`
  26. }
  27. } else {
  28. arg.children.unshift(`${context.helperString(CAMELIZE)}(`)
  29. arg.children.push(`)`)
  30. }
  31. }
  32. if (
  33. !exp ||
  34. (exp.type === NodeTypes.SIMPLE_EXPRESSION && !exp.content.trim())
  35. ) {
  36. context.onError(createCompilerError(ErrorCodes.X_V_BIND_NO_EXPRESSION, loc))
  37. return {
  38. props: [createObjectProperty(arg!, createSimpleExpression('', true, loc))]
  39. }
  40. }
  41. return {
  42. props: [createObjectProperty(arg!, exp)]
  43. }
  44. }