no-confusing-v-for-v-if.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. // Helpers
  13. // ------------------------------------------------------------------------------
  14. /**
  15. * Check whether the given `v-if` node is using the variable which is defined by the `v-for` directive.
  16. * @param {VDirective} vIf The `v-if` attribute node to check.
  17. * @returns {boolean} `true` if the `v-if` is using the variable which is defined by the `v-for` directive.
  18. */
  19. function isUsingIterationVar(vIf) {
  20. const element = vIf.parent.parent
  21. return Boolean(
  22. vIf.value &&
  23. vIf.value.references.some((reference) =>
  24. element.variables.some(
  25. (variable) =>
  26. variable.id.name === reference.id.name && variable.kind === 'v-for'
  27. )
  28. )
  29. )
  30. }
  31. // ------------------------------------------------------------------------------
  32. // Rule Definition
  33. // ------------------------------------------------------------------------------
  34. module.exports = {
  35. meta: {
  36. type: 'suggestion',
  37. docs: {
  38. description: 'disallow confusing `v-for` and `v-if` on the same element',
  39. categories: ['vue3-recommended', 'recommended'],
  40. url: 'https://eslint.vuejs.org/rules/no-confusing-v-for-v-if.html'
  41. },
  42. deprecated: true,
  43. replacedBy: ['no-use-v-if-with-v-for'],
  44. fixable: null,
  45. schema: []
  46. },
  47. /** @param {RuleContext} context */
  48. create(context) {
  49. return utils.defineTemplateBodyVisitor(context, {
  50. "VAttribute[directive=true][key.name.name='if']"(node) {
  51. const element = node.parent.parent
  52. if (utils.hasDirective(element, 'for') && !isUsingIterationVar(node)) {
  53. context.report({
  54. node,
  55. loc: node.loc,
  56. message: "This 'v-if' should be moved to the wrapper element."
  57. })
  58. }
  59. }
  60. })
  61. }
  62. }