v-bind-style.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. const utils = require('../utils')
  8. module.exports = {
  9. meta: {
  10. type: 'suggestion',
  11. docs: {
  12. description: 'enforce `v-bind` directive style',
  13. categories: ['vue3-strongly-recommended', 'strongly-recommended'],
  14. url: 'https://eslint.vuejs.org/rules/v-bind-style.html'
  15. },
  16. fixable: 'code',
  17. schema: [{ enum: ['shorthand', 'longform'] }]
  18. },
  19. /** @param {RuleContext} context */
  20. create(context) {
  21. const preferShorthand = context.options[0] !== 'longform'
  22. return utils.defineTemplateBodyVisitor(context, {
  23. /** @param {VDirective} node */
  24. "VAttribute[directive=true][key.name.name='bind'][key.argument!=null]"(
  25. node
  26. ) {
  27. const shorthandProp = node.key.name.rawName === '.'
  28. const shorthand = node.key.name.rawName === ':' || shorthandProp
  29. if (shorthand === preferShorthand) {
  30. return
  31. }
  32. let message = "Expected 'v-bind' before ':'."
  33. if (preferShorthand) {
  34. message = "Unexpected 'v-bind' before ':'."
  35. } else if (shorthandProp) {
  36. message = "Expected 'v-bind:' instead of '.'."
  37. }
  38. context.report({
  39. node,
  40. loc: node.loc,
  41. message,
  42. *fix(fixer) {
  43. if (preferShorthand) {
  44. yield fixer.remove(node.key.name)
  45. } else {
  46. yield fixer.insertTextBefore(node, 'v-bind')
  47. if (shorthandProp) {
  48. // Replace `.` by `:`.
  49. yield fixer.replaceText(node.key.name, ':')
  50. // Insert `.prop` modifier if it doesn't exist.
  51. const modifier = node.key.modifiers[0]
  52. const isAutoGeneratedPropModifier =
  53. modifier.name === 'prop' && modifier.rawName === ''
  54. if (isAutoGeneratedPropModifier) {
  55. yield fixer.insertTextBefore(modifier, '.prop')
  56. }
  57. }
  58. }
  59. }
  60. })
  61. }
  62. })
  63. }
  64. }