no-template-key.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. const utils = require('../utils')
  8. module.exports = {
  9. meta: {
  10. type: 'problem',
  11. docs: {
  12. description: 'disallow `key` attribute on `<template>`',
  13. categories: ['vue3-essential', 'vue2-essential'],
  14. url: 'https://eslint.vuejs.org/rules/no-template-key.html'
  15. },
  16. fixable: null,
  17. schema: [],
  18. messages: {
  19. disallow:
  20. "'<template>' cannot be keyed. Place the key on real elements instead."
  21. }
  22. },
  23. /** @param {RuleContext} context */
  24. create(context) {
  25. return utils.defineTemplateBodyVisitor(context, {
  26. /** @param {VElement} node */
  27. "VElement[name='template']"(node) {
  28. const keyNode =
  29. utils.getAttribute(node, 'key') ||
  30. utils.getDirective(node, 'bind', 'key')
  31. if (keyNode) {
  32. if (utils.hasDirective(node, 'for')) {
  33. // It's valid for Vue.js 3.x.
  34. // <template v-for="item in list" :key="item.id"> ... </template>
  35. // see https://github.com/vuejs/vue-next/issues/1734
  36. return
  37. }
  38. context.report({
  39. node: keyNode,
  40. loc: keyNode.loc,
  41. messageId: 'disallow'
  42. })
  43. }
  44. }
  45. })
  46. }
  47. }