no-template-shadow.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * @fileoverview Disallow variable declarations from shadowing variables declared in the outer scope.
  3. * @author Armano
  4. */
  5. 'use strict'
  6. // ------------------------------------------------------------------------------
  7. // Requirements
  8. // ------------------------------------------------------------------------------
  9. const utils = require('../utils')
  10. // ------------------------------------------------------------------------------
  11. // Rule Definition
  12. // ------------------------------------------------------------------------------
  13. const GROUP_NAMES = ['props', 'computed', 'data', 'methods']
  14. module.exports = {
  15. meta: {
  16. type: 'suggestion',
  17. docs: {
  18. description: 'disallow variable declarations from shadowing variables declared in the outer scope',
  19. category: 'strongly-recommended',
  20. url: 'https://eslint.vuejs.org/rules/no-template-shadow.html'
  21. },
  22. fixable: null,
  23. schema: []
  24. },
  25. create (context) {
  26. const jsVars = new Set()
  27. let scope = {
  28. parent: null,
  29. nodes: []
  30. }
  31. // ----------------------------------------------------------------------
  32. // Public
  33. // ----------------------------------------------------------------------
  34. return utils.defineTemplateBodyVisitor(context, {
  35. VElement (node) {
  36. scope = {
  37. parent: scope,
  38. nodes: scope.nodes.slice() // make copy
  39. }
  40. if (node.variables) {
  41. for (const variable of node.variables) {
  42. const varNode = variable.id
  43. const name = varNode.name
  44. if (scope.nodes.some(node => node.name === name) || jsVars.has(name)) {
  45. context.report({
  46. node: varNode,
  47. loc: varNode.loc,
  48. message: "Variable '{{name}}' is already declared in the upper scope.",
  49. data: {
  50. name
  51. }
  52. })
  53. } else {
  54. scope.nodes.push(varNode)
  55. }
  56. }
  57. }
  58. },
  59. 'VElement:exit' (node) {
  60. scope = scope.parent
  61. }
  62. }, utils.executeOnVue(context, (obj) => {
  63. const properties = Array.from(utils.iterateProperties(obj, new Set(GROUP_NAMES)))
  64. for (const node of properties) {
  65. jsVars.add(node.name)
  66. }
  67. }))
  68. }
  69. }