no-v-text-v-html-on-component.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * @author Yosuke Ota
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. const casing = require('../utils/casing')
  8. module.exports = {
  9. meta: {
  10. type: 'problem',
  11. docs: {
  12. description: 'disallow v-text / v-html on component',
  13. categories: ['vue2-essential', 'vue3-essential'],
  14. url: 'https://eslint.vuejs.org/rules/no-v-text-v-html-on-component.html'
  15. },
  16. fixable: null,
  17. schema: [
  18. {
  19. type: 'object',
  20. properties: {
  21. allow: {
  22. type: 'array',
  23. items: {
  24. type: 'string'
  25. },
  26. uniqueItems: true
  27. },
  28. ignoreElementNamespaces: {
  29. type: 'boolean'
  30. }
  31. },
  32. additionalProperties: false
  33. }
  34. ],
  35. messages: {
  36. disallow:
  37. "Using {{directiveName}} on component may break component's content."
  38. }
  39. },
  40. /** @param {RuleContext} context */
  41. create(context) {
  42. const options = context.options[0] || {}
  43. /** @type {Set<string>} */
  44. const allow = new Set(options.allow)
  45. /** @type {boolean} */
  46. const ignoreElementNamespaces = options.ignoreElementNamespaces === true
  47. /**
  48. * Check whether the given node is an allowed component or not.
  49. * @param {VElement} node The start tag node to check.
  50. * @returns {boolean} `true` if the node is an allowed component.
  51. */
  52. function isAllowedComponent(node) {
  53. const componentName = node.rawName
  54. return (
  55. allow.has(componentName) ||
  56. allow.has(casing.pascalCase(componentName)) ||
  57. allow.has(casing.kebabCase(componentName))
  58. )
  59. }
  60. /**
  61. * Verify for v-text and v-html directive
  62. * @param {VDirective} node
  63. */
  64. function verify(node) {
  65. const element = node.parent.parent
  66. if (
  67. utils.isCustomComponent(element, ignoreElementNamespaces) &&
  68. !isAllowedComponent(element)
  69. ) {
  70. context.report({
  71. node,
  72. loc: node.loc,
  73. messageId: 'disallow',
  74. data: {
  75. directiveName: `v-${node.key.name.name}`
  76. }
  77. })
  78. }
  79. }
  80. return utils.defineTemplateBodyVisitor(context, {
  81. "VAttribute[directive=true][key.name.name='text']": verify,
  82. "VAttribute[directive=true][key.name.name='html']": verify
  83. })
  84. }
  85. }