v-bind-style.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * @author Toru Nagashima
  3. * @copyright 2017 Toru Nagashima. All rights reserved.
  4. * See LICENSE file in root directory for full license.
  5. */
  6. 'use strict'
  7. // ------------------------------------------------------------------------------
  8. // Requirements
  9. // ------------------------------------------------------------------------------
  10. const utils = require('../utils')
  11. // ------------------------------------------------------------------------------
  12. // Rule Definition
  13. // ------------------------------------------------------------------------------
  14. module.exports = {
  15. meta: {
  16. type: 'suggestion',
  17. docs: {
  18. description: 'enforce `v-bind` directive style',
  19. categories: ['vue3-strongly-recommended', 'strongly-recommended'],
  20. url: 'https://eslint.vuejs.org/rules/v-bind-style.html'
  21. },
  22. fixable: 'code',
  23. schema: [{ enum: ['shorthand', 'longform'] }]
  24. },
  25. /** @param {RuleContext} context */
  26. create(context) {
  27. const preferShorthand = context.options[0] !== 'longform'
  28. return utils.defineTemplateBodyVisitor(context, {
  29. /** @param {VDirective} node */
  30. "VAttribute[directive=true][key.name.name='bind'][key.argument!=null]"(
  31. node
  32. ) {
  33. const shorthandProp = node.key.name.rawName === '.'
  34. const shorthand = node.key.name.rawName === ':' || shorthandProp
  35. if (shorthand === preferShorthand) {
  36. return
  37. }
  38. context.report({
  39. node,
  40. loc: node.loc,
  41. message: preferShorthand
  42. ? "Unexpected 'v-bind' before ':'."
  43. : shorthandProp
  44. ? "Expected 'v-bind:' instead of '.'."
  45. : /* otherwise */ "Expected 'v-bind' before ':'.",
  46. *fix(fixer) {
  47. if (preferShorthand) {
  48. yield fixer.remove(node.key.name)
  49. } else {
  50. yield fixer.insertTextBefore(node, 'v-bind')
  51. if (shorthandProp) {
  52. // Replace `.` by `:`.
  53. yield fixer.replaceText(node.key.name, ':')
  54. // Insert `.prop` modifier if it doesn't exist.
  55. const modifier = node.key.modifiers[0]
  56. const isAutoGeneratedPropModifier =
  57. modifier.name === 'prop' && modifier.rawName === ''
  58. if (isAutoGeneratedPropModifier) {
  59. yield fixer.insertTextBefore(modifier, '.prop')
  60. }
  61. }
  62. }
  63. }
  64. })
  65. }
  66. })
  67. }
  68. }