require-v-for-key.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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: 'require `v-bind:key` with `v-for` directives',
  13. categories: ['vue3-essential', 'essential'],
  14. url: 'https://eslint.vuejs.org/rules/require-v-for-key.html'
  15. },
  16. fixable: null,
  17. schema: []
  18. },
  19. /** @param {RuleContext} context */
  20. create(context) {
  21. /**
  22. * Check the given element about `v-bind:key` attributes.
  23. * @param {VElement} element The element node to check.
  24. */
  25. function checkKey(element) {
  26. if (utils.hasDirective(element, 'bind', 'key')) {
  27. return
  28. }
  29. if (element.name === 'template' || element.name === 'slot') {
  30. for (const child of element.children) {
  31. if (child.type === 'VElement') {
  32. checkKey(child)
  33. }
  34. }
  35. } else if (!utils.isCustomComponent(element)) {
  36. context.report({
  37. node: element.startTag,
  38. loc: element.startTag.loc,
  39. message:
  40. "Elements in iteration expect to have 'v-bind:key' directives."
  41. })
  42. }
  43. }
  44. return utils.defineTemplateBodyVisitor(context, {
  45. /** @param {VDirective} node */
  46. "VAttribute[directive=true][key.name.name='for']"(node) {
  47. checkKey(node.parent.parent)
  48. }
  49. })
  50. }
  51. }