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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 {ASTNode} 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 vIf.value.references.some(reference =>
  22. element.variables.some(variable =>
  23. variable.id.name === reference.id.name &&
  24. variable.kind === 'v-for'
  25. )
  26. )
  27. }
  28. // ------------------------------------------------------------------------------
  29. // Rule Definition
  30. // ------------------------------------------------------------------------------
  31. module.exports = {
  32. meta: {
  33. type: 'suggestion',
  34. docs: {
  35. description: 'disallow confusing `v-for` and `v-if` on the same element',
  36. category: 'recommended',
  37. url: 'https://eslint.vuejs.org/rules/no-confusing-v-for-v-if.html',
  38. replacedBy: ['no-use-v-if-with-v-for']
  39. },
  40. deprecated: true,
  41. fixable: null,
  42. schema: []
  43. },
  44. create (context) {
  45. return utils.defineTemplateBodyVisitor(context, {
  46. "VAttribute[directive=true][key.name='if']" (node) {
  47. const element = node.parent.parent
  48. if (utils.hasDirective(element, 'for') && !isUsingIterationVar(node)) {
  49. context.report({
  50. node,
  51. loc: node.loc,
  52. message: "This 'v-if' should be moved to the wrapper element."
  53. })
  54. }
  55. }
  56. })
  57. }
  58. }