no-template-key.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @author Toru Nagashima
  3. * @copyright 2016 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: 'disallow `key` attribute on `<template>`',
  19. categories: ['vue3-essential', 'essential'],
  20. url: 'https://eslint.vuejs.org/rules/no-template-key.html'
  21. },
  22. fixable: null,
  23. schema: [],
  24. messages: {
  25. disallow:
  26. "'<template>' cannot be keyed. Place the key on real elements instead."
  27. }
  28. },
  29. /** @param {RuleContext} context */
  30. create(context) {
  31. return utils.defineTemplateBodyVisitor(context, {
  32. /** @param {VElement} node */
  33. "VElement[name='template']"(node) {
  34. const keyNode =
  35. utils.getAttribute(node, 'key') ||
  36. utils.getDirective(node, 'bind', 'key')
  37. if (keyNode) {
  38. if (utils.hasDirective(node, 'for')) {
  39. // It's valid for Vue.js 3.x.
  40. // <template v-for="item in list" :key="item.id"> ... </template>
  41. // see https://github.com/vuejs/vue-next/issues/1734
  42. return
  43. }
  44. context.report({
  45. node: keyNode,
  46. loc: keyNode.loc,
  47. messageId: 'disallow'
  48. })
  49. }
  50. }
  51. })
  52. }
  53. }