no-shared-component-data.js 2.2 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. module.exports = {
  35. meta: {
  36. type: 'problem',
  37. docs: {
  38. description: "enforce component's data property to be a function",
  39. categories: ['vue3-essential', 'vue2-essential'],
  40. url: 'https://eslint.vuejs.org/rules/no-shared-component-data.html'
  41. },
  42. fixable: 'code',
  43. schema: [],
  44. messages: {
  45. dataPropertyMustBeFunction:
  46. '`data` property in component must be a function.'
  47. }
  48. },
  49. /** @param {RuleContext} context */
  50. create(context) {
  51. const sourceCode = context.getSourceCode()
  52. return utils.executeOnVueComponent(context, (obj) => {
  53. const invalidData = utils.findProperty(
  54. obj,
  55. 'data',
  56. (p) =>
  57. p.value.type !== 'FunctionExpression' &&
  58. p.value.type !== 'ArrowFunctionExpression' &&
  59. p.value.type !== 'Identifier'
  60. )
  61. if (invalidData) {
  62. context.report({
  63. node: invalidData,
  64. messageId: 'dataPropertyMustBeFunction',
  65. fix(fixer) {
  66. const tokens = getFirstAndLastTokens(invalidData.value, sourceCode)
  67. return [
  68. fixer.insertTextBefore(tokens.first, 'function() {\nreturn '),
  69. fixer.insertTextAfter(tokens.last, ';\n}')
  70. ]
  71. }
  72. })
  73. }
  74. })
  75. }
  76. }