Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add vue/no-computed-properties-in-data rule #1653

Merged
merged 1 commit into from Oct 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/rules/README.md
Expand Up @@ -300,6 +300,7 @@ For example:
| [vue/next-tick-style](./next-tick-style.md) | enforce Promise or callback style in `nextTick` | :wrench: |
| [vue/no-bare-strings-in-template](./no-bare-strings-in-template.md) | disallow the use of bare strings in `<template>` | |
| [vue/no-boolean-default](./no-boolean-default.md) | disallow boolean defaults | :wrench: |
| [vue/no-computed-properties-in-data](./no-computed-properties-in-data.md) | disallow accessing computed properties in `data`. | |
| [vue/no-deprecated-v-is](./no-deprecated-v-is.md) | disallow deprecated `v-is` directive (in Vue.js 3.1.0+) | :wrench: |
| [vue/no-duplicate-attr-inheritance](./no-duplicate-attr-inheritance.md) | enforce `inheritAttrs` to be set to `false` when using `v-bind="$attrs"` | |
| [vue/no-empty-component-block](./no-empty-component-block.md) | disallow the `<template>` `<script>` `<style>` block to be empty | |
Expand Down
45 changes: 45 additions & 0 deletions docs/rules/no-computed-properties-in-data.md
@@ -0,0 +1,45 @@
---
pageClass: rule-details
sidebarDepth: 0
title: vue/no-computed-properties-in-data
description: disallow accessing computed properties in `data`.
---
# vue/no-computed-properties-in-data

> disallow accessing computed properties in `data`.

- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> ***This rule has not been released yet.*** </badge>

## :book: Rule Details

This rule disallow accessing computed properties in `data()`.
The computed property cannot be accessed in `data()` because is before initialization.

<eslint-code-block :rules="{'vue/no-computed-properties-in-data': ['error']}">

```vue
<script>
export default {
data() {
return {
/* ✗ BAD */
bar: this.foo
}
},
computed: {
foo () {}
}
}
</script>
```

</eslint-code-block>

## :wrench: Options

Nothing.

## :mag: Implementation

- [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/no-computed-properties-in-data.js)
- [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/no-computed-properties-in-data.js)
1 change: 1 addition & 0 deletions lib/index.js
Expand Up @@ -56,6 +56,7 @@ module.exports = {
'no-async-in-computed-properties': require('./rules/no-async-in-computed-properties'),
'no-bare-strings-in-template': require('./rules/no-bare-strings-in-template'),
'no-boolean-default': require('./rules/no-boolean-default'),
'no-computed-properties-in-data': require('./rules/no-computed-properties-in-data'),
'no-confusing-v-for-v-if': require('./rules/no-confusing-v-for-v-if'),
'no-constant-condition': require('./rules/no-constant-condition'),
'no-custom-modifiers-on-v-model': require('./rules/no-custom-modifiers-on-v-model'),
Expand Down
108 changes: 108 additions & 0 deletions lib/rules/no-computed-properties-in-data.js
@@ -0,0 +1,108 @@
/**
* @author Yosuke Ota
* See LICENSE file in root directory for full license.
*/
'use strict'

// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------

const utils = require('../utils')

/**
* @typedef {import('../utils').VueObjectData} VueObjectData
*/

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------

module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow accessing computed properties in `data`.',
categories: undefined,
url: 'https://eslint.vuejs.org/rules/no-computed-properties-in-data.html'
},
fixable: null,
schema: [],
messages: {
cannotBeUsed:
'The computed property cannot be used in `data()` because it is before initialization.'
}
},
/** @param {RuleContext} context */
create(context) {
/** @type {Map<ObjectExpression, {data: FunctionExpression | ArrowFunctionExpression, computedNames:Set<string>}>} */
const contextMap = new Map()

/**
* @typedef {object} ScopeStack
* @property {ScopeStack | null} upper
* @property {FunctionExpression | FunctionDeclaration | ArrowFunctionExpression} node
*/
/** @type {ScopeStack | null} */
let scopeStack = null

return utils.compositingVisitors(
{
/**
* @param {FunctionExpression | FunctionDeclaration | ArrowFunctionExpression} node
*/
':function'(node) {
scopeStack = {
upper: scopeStack,
node
}
},
':function:exit'() {
scopeStack = scopeStack && scopeStack.upper
}
},
utils.defineVueVisitor(context, {
onVueObjectEnter(node) {
const dataProperty = utils.findProperty(node, 'data')
if (
!dataProperty ||
(dataProperty.value.type !== 'FunctionExpression' &&
dataProperty.value.type !== 'ArrowFunctionExpression')
) {
return
}
const computedNames = new Set()
for (const computed of utils.iterateProperties(
node,
new Set(['computed'])
)) {
computedNames.add(computed.name)
}

contextMap.set(node, { data: dataProperty.value, computedNames })
},
/**
* @param {MemberExpression} node
* @param {VueObjectData} vueData
*/
MemberExpression(node, vueData) {
if (!scopeStack || !utils.isThis(node.object, context)) {
return
}
const ctx = contextMap.get(vueData.node)
if (!ctx || ctx.data !== scopeStack.node) {
return
}
const name = utils.getStaticPropertyName(node)
if (!name || !ctx.computedNames.has(name)) {
return
}
context.report({
node,
messageId: 'cannotBeUsed'
})
}
})
)
}
}
130 changes: 130 additions & 0 deletions tests/lib/rules/no-computed-properties-in-data.js
@@ -0,0 +1,130 @@
/**
* @author Yosuke Ota
* See LICENSE file in root directory for full license.
*/
'use strict'

const RuleTester = require('eslint').RuleTester
const rule = require('../../../lib/rules/no-computed-properties-in-data')

const tester = new RuleTester({
parser: require.resolve('vue-eslint-parser'),
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module'
}
})

tester.run('no-computed-properties-in-data', rule, {
valid: [
{
filename: 'test.vue',
code: `
<script>
export default {
data() {
const foo = this.foo
return {}
}
}
</script>
`
},
{
filename: 'test.vue',
code: `
<script>
export default {
data() {
const foo = this.foo()
return {}
},
methods: {
foo() {}
}
}
</script>
`
},
{
filename: 'test.vue',
code: `
<script>
export default {
props: ['foo'],
data() {
const foo = this.foo
return {}
},
}
</script>
`
},
{
filename: 'test.vue',
code: `
<script>
export default {
data: {
foo: this.foo
},
computed: {
foo () {}
}
}
</script>
`
}
],
invalid: [
{
filename: 'test.vue',
code: `
<script>
export default {
data() {
const foo = this.foo
return {}
},
computed: {
foo () {}
}
}
</script>
`,
errors: [
{
message:
'The computed property cannot be used in `data()` because it is before initialization.',
line: 5,
column: 23
}
]
},
{
filename: 'test.vue',
code: `
<script>
export default {
data() {
const vm = this
const foo = vm.foo
return {}
},
computed: {
foo () {}
}
}
</script>
`,
errors: [
{
message:
'The computed property cannot be used in `data()` because it is before initialization.',
line: 6,
column: 23
}
]
}
]
})
2 changes: 1 addition & 1 deletion tools/new-rule.js
Expand Up @@ -32,7 +32,7 @@ const logger = console
// Requirements
// ------------------------------------------------------------------------------

// ...
const utils = require('../utils')

// ------------------------------------------------------------------------------
// Helpers
Expand Down