valid-v-if.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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: 'problem',
  11. docs: {
  12. description: 'enforce valid `v-if` directives',
  13. categories: ['vue3-essential', 'vue2-essential'],
  14. url: 'https://eslint.vuejs.org/rules/valid-v-if.html'
  15. },
  16. fixable: null,
  17. schema: [],
  18. messages: {
  19. withVElse:
  20. "'v-if' and 'v-else' directives can't exist on the same element. You may want 'v-else-if' directives.",
  21. withVElseIf:
  22. "'v-if' and 'v-else-if' directives can't exist on the same element.",
  23. unexpectedArgument: "'v-if' directives require no argument.",
  24. unexpectedModifier: "'v-if' directives require no modifier.",
  25. expectedValue: "'v-if' directives require that attribute value."
  26. }
  27. },
  28. /** @param {RuleContext} context */
  29. create(context) {
  30. return utils.defineTemplateBodyVisitor(context, {
  31. /** @param {VDirective} node */
  32. "VAttribute[directive=true][key.name.name='if']"(node) {
  33. const element = node.parent.parent
  34. if (utils.hasDirective(element, 'else')) {
  35. context.report({
  36. node,
  37. messageId: 'withVElse'
  38. })
  39. }
  40. if (utils.hasDirective(element, 'else-if')) {
  41. context.report({
  42. node,
  43. messageId: 'withVElseIf'
  44. })
  45. }
  46. if (node.key.argument) {
  47. context.report({
  48. node: node.key.argument,
  49. messageId: 'unexpectedArgument'
  50. })
  51. }
  52. if (node.key.modifiers.length > 0) {
  53. context.report({
  54. node,
  55. loc: {
  56. start: node.key.modifiers[0].loc.start,
  57. end: node.key.modifiers[node.key.modifiers.length - 1].loc.end
  58. },
  59. messageId: 'unexpectedModifier'
  60. })
  61. }
  62. if (!node.value || utils.isEmptyValueDirective(node, context)) {
  63. context.report({
  64. node,
  65. messageId: 'expectedValue'
  66. })
  67. }
  68. }
  69. })
  70. }
  71. }