no-shared-component-data.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * @fileoverview Enforces component's data property to be a function.
  3. * @author Armano
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. /** @param {Token} token */
  8. function isOpenParen(token) {
  9. return token.type === 'Punctuator' && token.value === '('
  10. }
  11. /** @param {Token} token */
  12. function isCloseParen(token) {
  13. return token.type === 'Punctuator' && token.value === ')'
  14. }
  15. /**
  16. * @param {Expression} node
  17. * @param {SourceCode} sourceCode
  18. */
  19. function getFirstAndLastTokens(node, sourceCode) {
  20. let first = sourceCode.getFirstToken(node)
  21. let last = sourceCode.getLastToken(node)
  22. // If the value enclosed by parentheses, update the 'first' and 'last' by the parentheses.
  23. while (true) {
  24. const prev = sourceCode.getTokenBefore(first)
  25. const next = sourceCode.getTokenAfter(last)
  26. if (isOpenParen(prev) && isCloseParen(next)) {
  27. first = prev
  28. last = next
  29. } else {
  30. return { first, last }
  31. }
  32. }
  33. }
  34. // ------------------------------------------------------------------------------
  35. // Rule Definition
  36. // ------------------------------------------------------------------------------
  37. module.exports = {
  38. meta: {
  39. type: 'problem',
  40. docs: {
  41. description: "enforce component's data property to be a function",
  42. categories: ['vue3-essential', 'essential'],
  43. url: 'https://eslint.vuejs.org/rules/no-shared-component-data.html'
  44. },
  45. fixable: 'code',
  46. schema: []
  47. },
  48. /** @param {RuleContext} context */
  49. create(context) {
  50. const sourceCode = context.getSourceCode()
  51. return utils.executeOnVueComponent(context, (obj) => {
  52. const invalidData = utils.findProperty(
  53. obj,
  54. 'data',
  55. (p) =>
  56. p.value.type !== 'FunctionExpression' &&
  57. p.value.type !== 'ArrowFunctionExpression' &&
  58. p.value.type !== 'Identifier'
  59. )
  60. if (invalidData) {
  61. context.report({
  62. node: invalidData,
  63. message: '`data` property in component must be a function.',
  64. fix(fixer) {
  65. const tokens = getFirstAndLastTokens(invalidData.value, sourceCode)
  66. return [
  67. fixer.insertTextBefore(tokens.first, 'function() {\nreturn '),
  68. fixer.insertTextAfter(tokens.last, ';\n}')
  69. ]
  70. }
  71. })
  72. }
  73. })
  74. }
  75. }