v-on-style.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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-on` directive style',
  13. categories: ['vue3-strongly-recommended', 'vue2-strongly-recommended'],
  14. url: 'https://eslint.vuejs.org/rules/v-on-style.html'
  15. },
  16. fixable: 'code',
  17. schema: [{ enum: ['shorthand', 'longform'] }],
  18. messages: {
  19. expectedShorthand: "Expected '@' instead of 'v-on:'.",
  20. expectedLonghand: "Expected 'v-on:' instead of '@'."
  21. }
  22. },
  23. /** @param {RuleContext} context */
  24. create(context) {
  25. const preferShorthand = context.options[0] !== 'longform'
  26. return utils.defineTemplateBodyVisitor(context, {
  27. /** @param {VDirective} node */
  28. "VAttribute[directive=true][key.name.name='on'][key.argument!=null]"(
  29. node
  30. ) {
  31. const shorthand = node.key.name.rawName === '@'
  32. if (shorthand === preferShorthand) {
  33. return
  34. }
  35. const pos = node.range[0]
  36. context.report({
  37. node,
  38. loc: node.loc,
  39. messageId: preferShorthand ? 'expectedShorthand' : 'expectedLonghand',
  40. fix: (fixer) =>
  41. preferShorthand
  42. ? fixer.replaceTextRange([pos, pos + 5], '@')
  43. : fixer.replaceTextRange([pos, pos + 1], 'v-on:')
  44. })
  45. }
  46. })
  47. }
  48. }