require-v-for-key.js 1.5 KB

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