no-shared-component-data.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. function isOpenParen (token) {
  8. return token.type === 'Punctuator' && token.value === '('
  9. }
  10. function isCloseParen (token) {
  11. return token.type === 'Punctuator' && token.value === ')'
  12. }
  13. function getFirstAndLastTokens (node, sourceCode) {
  14. let first = sourceCode.getFirstToken(node)
  15. let last = sourceCode.getLastToken(node)
  16. // If the value enclosed by parentheses, update the 'first' and 'last' by the parentheses.
  17. while (true) {
  18. const prev = sourceCode.getTokenBefore(first)
  19. const next = sourceCode.getTokenAfter(last)
  20. if (isOpenParen(prev) && isCloseParen(next)) {
  21. first = prev
  22. last = next
  23. } else {
  24. return { first, last }
  25. }
  26. }
  27. }
  28. // ------------------------------------------------------------------------------
  29. // Rule Definition
  30. // ------------------------------------------------------------------------------
  31. module.exports = {
  32. meta: {
  33. type: 'problem',
  34. docs: {
  35. description: "enforce component's data property to be a function",
  36. category: 'essential',
  37. url: 'https://eslint.vuejs.org/rules/no-shared-component-data.html'
  38. },
  39. fixable: 'code',
  40. schema: []
  41. },
  42. create (context) {
  43. const sourceCode = context.getSourceCode()
  44. return utils.executeOnVueComponent(context, (obj) => {
  45. obj.properties
  46. .filter(p =>
  47. p.type === 'Property' &&
  48. p.key.type === 'Identifier' &&
  49. p.key.name === 'data' &&
  50. p.value.type !== 'FunctionExpression' &&
  51. p.value.type !== 'ArrowFunctionExpression' &&
  52. p.value.type !== 'Identifier'
  53. )
  54. .forEach(p => {
  55. context.report({
  56. node: p,
  57. message: '`data` property in component must be a function.',
  58. fix (fixer) {
  59. const tokens = getFirstAndLastTokens(p.value, sourceCode)
  60. return [
  61. fixer.insertTextBefore(tokens.first, 'function() {\nreturn '),
  62. fixer.insertTextAfter(tokens.last, ';\n}')
  63. ]
  64. }
  65. })
  66. })
  67. })
  68. }
  69. }