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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. },
  29. additionalProperties: false
  30. }
  31. ],
  32. messages: {
  33. disallow:
  34. "Using {{directiveName}} on component may break component's content."
  35. }
  36. },
  37. /** @param {RuleContext} context */
  38. create(context) {
  39. const options = context.options[0] || {}
  40. /** @type {Set<string>} */
  41. const allow = new Set(options.allow)
  42. /**
  43. * Check whether the given node is an allowed component or not.
  44. * @param {VElement} node The start tag node to check.
  45. * @returns {boolean} `true` if the node is an allowed component.
  46. */
  47. function isAllowedComponent(node) {
  48. const componentName = node.rawName
  49. return (
  50. allow.has(componentName) ||
  51. allow.has(casing.pascalCase(componentName)) ||
  52. allow.has(casing.kebabCase(componentName))
  53. )
  54. }
  55. /**
  56. * Verify for v-text and v-html directive
  57. * @param {VDirective} node
  58. */
  59. function verify(node) {
  60. const element = node.parent.parent
  61. if (utils.isCustomComponent(element) && !isAllowedComponent(element)) {
  62. context.report({
  63. node,
  64. loc: node.loc,
  65. messageId: 'disallow',
  66. data: {
  67. directiveName: `v-${node.key.name.name}`
  68. }
  69. })
  70. }
  71. }
  72. return utils.defineTemplateBodyVisitor(context, {
  73. "VAttribute[directive=true][key.name.name='text']": verify,
  74. "VAttribute[directive=true][key.name.name='html']": verify
  75. })
  76. }
  77. }