v-bind-style.js 2.3 KB

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