require-v-for-key.js 1.7 KB

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