require-v-for-key.js 1.8 KB

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