123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- 'use strict'
- const utils = require('../utils')
- function isOpenParen(token) {
- return token.type === 'Punctuator' && token.value === '('
- }
- function isCloseParen(token) {
- return token.type === 'Punctuator' && token.value === ')'
- }
- function getFirstAndLastTokens(node, sourceCode) {
- let first = sourceCode.getFirstToken(node)
- let last = sourceCode.getLastToken(node)
-
- while (true) {
- const prev = sourceCode.getTokenBefore(first)
- const next = sourceCode.getTokenAfter(last)
- if (isOpenParen(prev) && isCloseParen(next)) {
- first = prev
- last = next
- } else {
- return { first, last }
- }
- }
- }
- module.exports = {
- meta: {
- type: 'problem',
- docs: {
- description: "enforce component's data property to be a function",
- categories: ['vue3-essential', 'essential'],
- url: 'https://eslint.vuejs.org/rules/no-shared-component-data.html'
- },
- fixable: 'code',
- schema: []
- },
-
- create(context) {
- const sourceCode = context.getSourceCode()
- return utils.executeOnVueComponent(context, (obj) => {
- const invalidData = utils.findProperty(
- obj,
- 'data',
- (p) =>
- p.value.type !== 'FunctionExpression' &&
- p.value.type !== 'ArrowFunctionExpression' &&
- p.value.type !== 'Identifier'
- )
- if (invalidData) {
- context.report({
- node: invalidData,
- message: '`data` property in component must be a function.',
- fix(fixer) {
- const tokens = getFirstAndLastTokens(invalidData.value, sourceCode)
- return [
- fixer.insertTextBefore(tokens.first, 'function() {\nreturn '),
- fixer.insertTextAfter(tokens.last, ';\n}')
- ]
- }
- })
- }
- })
- }
- }
|