v-on-function-call.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * @author Niklas Higi
  3. */
  4. 'use strict'
  5. // ------------------------------------------------------------------------------
  6. // Requirements
  7. // ------------------------------------------------------------------------------
  8. const utils = require('../utils')
  9. // ------------------------------------------------------------------------------
  10. // Rule Definition
  11. // ------------------------------------------------------------------------------
  12. module.exports = {
  13. meta: {
  14. type: 'suggestion',
  15. docs: {
  16. description: 'enforce or forbid parentheses after method calls without arguments in `v-on` directives',
  17. category: undefined,
  18. url: 'https://eslint.vuejs.org/rules/v-on-function-call.html'
  19. },
  20. fixable: 'code',
  21. schema: [
  22. { enum: ['always', 'never'] }
  23. ]
  24. },
  25. create (context) {
  26. const always = context.options[0] === 'always'
  27. return utils.defineTemplateBodyVisitor(context, {
  28. "VAttribute[directive=true][key.name='on'][key.argument!=null] > VExpressionContainer > Identifier" (node) {
  29. if (!always) return
  30. context.report({
  31. node,
  32. loc: node.loc,
  33. message: "Method calls inside of 'v-on' directives must have parentheses."
  34. })
  35. },
  36. "VAttribute[directive=true][key.name='on'][key.argument!=null] VOnExpression > ExpressionStatement > *" (node) {
  37. if (!always && node.type === 'CallExpression' && node.arguments.length === 0) {
  38. context.report({
  39. node,
  40. loc: node.loc,
  41. message: "Method calls without arguments inside of 'v-on' directives must not have parentheses.",
  42. fix: fixer => {
  43. const nodeString = context.getSourceCode().getText().substring(node.range[0], node.range[1])
  44. // This ensures that parens are also removed if they contain whitespace
  45. const parensLength = nodeString.match(/\(\s*\)\s*$/)[0].length
  46. return fixer.removeRange([node.end - parensLength, node.end])
  47. }
  48. })
  49. }
  50. }
  51. })
  52. }
  53. }