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

feat: add prefer-use-template-ref rule #2554

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/rules/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,7 @@ For example:
| [vue/prefer-prop-type-boolean-first](./prefer-prop-type-boolean-first.md) | enforce `Boolean` comes first in component prop types | :bulb: | :warning: |
| [vue/prefer-separate-static-class](./prefer-separate-static-class.md) | require static class names in template to be in a separate `class` attribute | :wrench: | :hammer: |
| [vue/prefer-true-attribute-shorthand](./prefer-true-attribute-shorthand.md) | require shorthand form attribute when `v-bind` value is `true` | :bulb: | :hammer: |
| [vue/prefer-use-template-ref](./prefer-use-template-ref.md) | require using `useTemplateRef` over `ref` for template refs | :wrench: | :hammer: |
| [vue/require-default-export](./require-default-export.md) | require components to be the default export | | :warning: |
| [vue/require-direct-export](./require-direct-export.md) | require the component to be directly exported | | :hammer: |
| [vue/require-emit-validator](./require-emit-validator.md) | require type definitions in emits | :bulb: | :hammer: |
Expand Down
54 changes: 54 additions & 0 deletions docs/rules/prefer-use-template-ref.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
pageClass: rule-details
sidebarDepth: 0
title: vue/prefer-use-template-ref
description: require using `useTemplateRef` over `ref` for template refs
---

# vue/prefer-use-template-ref

> require using `useTemplateRef` over `ref` for template refs

- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> _**This rule has not been released yet.**_ </badge>
- :wrench: The `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the problems reported by this rule.

## :book: Rule Details

Vue 3.5 introduced a new way of obtaining template refs via
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this rule handle ref as a function? Can you add documentation for that?

<script setup>
  import { ref } from 'vue';
  const button = ref();
</script>

<template>
  <button :ref="ref => button.value = ref">Content</button>
</template>

the [useTemplateRef()](https://vuejs.org/guide/essentials/template-refs.html#accessing-the-refs) API.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
the [useTemplateRef()](https://vuejs.org/guide/essentials/template-refs.html#accessing-the-refs) API.
the [`useTemplateRef()`](https://vuejs.org/guide/essentials/template-refs.html#accessing-the-refs) API.


This rule enforces using the new `useTemplateRef` function over `ref` for template refs.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
This rule enforces using the new `useTemplateRef` function over `ref` for template refs.
This rule enforces using the new `useTemplateRef` function instead of `ref` for template refs.


<eslint-code-block fix :rules="{'vue/prefer-use-template-ref': ['error']}">

```vue

<template>
<div ref="divRef"></div>
<button ref="submitter">Submit</button>
</template>

<script>
import { ref, useTemplateRef } from 'vue';

/* ✓ GOOD */
const divRef = useTemplateRef('divRef');
const div = useTemplateRef('divRef');
const loremIpsum = useTemplateRef('divRef');
const submitButton = useTemplateRef('submitter');
/* ✗ BAD */
const divRef = ref();
const submitter = ref();
</script>
```
Comment on lines +24 to +43
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This currently fails anyway because of the duplicate const identifier, see https://deploy-preview-2554--eslint-plugin-vue.netlify.app/rules/prefer-use-template-ref.html.

Instead, I'd suggest something like this:

Suggested change
```vue
<template>
<div ref="divRef"></div>
<button ref="submitter">Submit</button>
</template>
<script>
import { ref, useTemplateRef } from 'vue';
/* ✓ GOOD */
const divRef = useTemplateRef('divRef');
const div = useTemplateRef('divRef');
const loremIpsum = useTemplateRef('divRef');
const submitButton = useTemplateRef('submitter');
/* ✗ BAD */
const divRef = ref();
const submitter = ref();
</script>
```
```vue
<template>
<button ref="submitRef">Submit</button>
<button ref="closeRef">Close</button>
</template>
<script>
import { ref, useTemplateRef } from 'vue';
/* ✓ GOOD */
const submitRef = useTemplateRef('submitRef');
const submitButton = useTemplateRef('submitRef');
const closeButton = useTemplateRef('closeRef');
/* ✗ BAD */
const closeRef = ref();
</script>
```


</eslint-code-block>

## :wrench: Options

Nothing.

## :mag: Implementation

- [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/prefer-use-template-ref.js)
- [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/prefer-use-template-ref.js)
1 change: 1 addition & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@
'prefer-separate-static-class': require('./rules/prefer-separate-static-class'),
'prefer-template': require('./rules/prefer-template'),
'prefer-true-attribute-shorthand': require('./rules/prefer-true-attribute-shorthand'),
'prefer-use-template-ref': require('./rules/prefer-use-template-ref'),
'prop-name-casing': require('./rules/prop-name-casing'),
'quote-props': require('./rules/quote-props'),
'require-component-is': require('./rules/require-component-is'),
Expand Down Expand Up @@ -281,7 +282,7 @@
vue: require('./processor')
},
environments: {
// TODO Remove in the next major version

Check warning on line 285 in lib/index.js

View workflow job for this annotation

GitHub Actions / Lint

Unexpected 'todo' comment: 'TODO Remove in the next major version'
/** @deprecated */
'setup-compiler-macros': {
globals: {
Expand Down
90 changes: 90 additions & 0 deletions lib/rules/prefer-use-template-ref.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* @author Thomasan1999
* See LICENSE file in root directory for full license.
*/
'use strict'

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

/** @type {import("eslint").Rule.RuleModule} */
module.exports = {
meta: {
type: 'suggestion',
docs: {
description:
'require using `useTemplateRef` over `ref` for template refs',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
'require using `useTemplateRef` over `ref` for template refs',
'require using `useTemplateRef` instead of `ref` for template refs',

Please re-run npm run update after this change to update the docs.

categories: undefined,
url: 'https://eslint.vuejs.org/rules/prefer-use-template-ref.html'
},
fixable: 'code',
schema: [],
messages: {
preferUseTemplateRef: "Replace 'ref' with 'useTemplateRef'."
}
},
/** @param {RuleContext} context */
create(context) {
/** @type Set<string> */
const templateRefs = new Set()

/**
* @typedef ScriptRef
* @type {{node: Expression, ref: string}}
*/

/**
* @type ScriptRef[] */
const scriptRefs = []

return utils.compositingVisitors(
utils.defineTemplateBodyVisitor(
context,
{
'VAttribute[directive=false]'(node) {
if (node.key.name === 'ref' && node.value?.value) {
templateRefs.add(node.value.value)
}
}
},
{
VariableDeclarator(declarator) {
// @ts-ignore
if (declarator.init?.callee?.name !== 'ref') {
return
}

scriptRefs.push({
node: declarator.init,
// @ts-ignore
ref: declarator.id.name
})
}
}
),
{
'Program:exit'() {
for (const templateRef of templateRefs) {
const scriptRef = scriptRefs.find(
(scriptRef) => scriptRef.ref === templateRef
)

if (!scriptRef) {
continue
}

context.report({
node: scriptRef.node,
messageId: 'preferUseTemplateRef',
fix(fixer) {
return fixer.replaceText(
scriptRef.node,
`useTemplateRef('${scriptRef.ref}')`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fix seems unsafe because it doesn't add any import statements. Adding import requires complex logic, so could you change it to without auto-fix to keep it simple?
If you want to implement autofix for import, please add tests for the absence and presence of import from 'vue', tests for different kinds of import, tests for the two type syntaxes in TypeScript, and tests combining them.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or you can change the autofix to a suggestion, so users still can apply it manually.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could add import if that's an option but I read in docs that ESLint rules should not apply complex logic. If you're okay with me adding it, I will implement the auto-fix with the added tests, it would definitely help me to have the auto-fix there when going through a bigger codebase to not have to do the change manually many times over and over. But if you prefer the suggestion option, I could also go with that. Wdyt?

)
}
})
}
}
}
)
}
}
232 changes: 232 additions & 0 deletions tests/lib/rules/prefer-use-template-ref.js
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add valid test cases that make sure the rule doesn't error/fail in the following cases:

  1. A .vue file with a ref that is not a template ref.
  2. A .js file with a ref.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please add some tests using the setup() function and some using the Options API?

Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
/**
* @author Thomasan1999
* See LICENSE file in root directory for full license.
*/
'use strict'

const RuleTester = require('../../eslint-compat').RuleTester
const rule = require('../../../lib/rules/prefer-use-template-ref')

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

tester.run('prefer-use-template-ref', rule, {
valid: [
{
filename: 'single-use-template-ref.vue',
code: `
<template>
<div ref="root" />
</template>

<script>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it is a <script setup> test, the setup attribute is required.

Suggested change
<script>
<script setup>

import { useTemplateRef } from 'vue';

const root = useTemplateRef('root');
</script>
`
},
{
filename: 'multiple-use-template-refs.vue',
code: `
<template>
<button ref="button">Content</button>
<a href="" ref="link">Link</a>
</template>

<script>
import { useTemplateRef } from 'vue';

const buttonRef = useTemplateRef('button');
const link = useTemplateRef('link');
</script>
`
},
{
filename: 'use-template-ref-in-block.vue',
code: `
<template>
<div>
<ul>
<li ref="firstListItem">Morning</li>
<li>Afternoon</li>
<li>Evening</li>
</ul>
</div>
</template>

<script>
import { useTemplateRef } from 'vue';

function getFirstListItemElement() {
const firstListItem = useTemplateRef('firstListItem');
}
</script>
`
}
],
invalid: [
{
filename: 'single-ref.vue',
code: `
<template>
<div ref="root"/>
</template>

<script>
import { ref } from 'vue';

const root = ref();
</script>
Comment on lines +77 to +85
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you make the code of the test cases a bit more concise please by removing the empty lines?

`,
output: `
<template>
<div ref="root"/>
</template>

<script>
import { ref } from 'vue';

const root = useTemplateRef('root');
</script>
`,
errors: [
{
messageId: 'preferUseTemplateRef',
line: 9,
column: 22
}
]
},
{
filename: 'one-ref-unused-in-script.vue',
code: `
<template>
<button ref="button">Content</button>
<a href="" ref="link">Link</a>
</template>

<script>
import { ref } from 'vue';

const buttonRef = ref();
const link = ref();
</script>
`,
output: `
<template>
<button ref="button">Content</button>
<a href="" ref="link">Link</a>
</template>

<script>
import { ref } from 'vue';

const buttonRef = ref();
const link = useTemplateRef('link');
</script>
`,
errors: [
{
messageId: 'preferUseTemplateRef',
line: 11,
column: 22
}
]
},
{
filename: 'multiple-refs.vue',
code: `
<template>
<h1 ref="heading">Heading</h1>
<a href="" ref="link">Link</a>
</template>

<script>
import { ref } from 'vue';

const heading = ref();
const link = ref();
</script>
`,
output: `
<template>
<h1 ref="heading">Heading</h1>
<a href="" ref="link">Link</a>
</template>

<script>
import { ref } from 'vue';

const heading = useTemplateRef('heading');
const link = useTemplateRef('link');
</script>
`,
errors: [
{
messageId: 'preferUseTemplateRef',
line: 10,
column: 25
},
{
messageId: 'preferUseTemplateRef',
line: 11,
column: 22
}
]
},
{
filename: 'ref-in-block.vue',
code: `
<template>
<div>
<ul>
<li ref="firstListItem">Morning</li>
<li>Afternoon</li>
<li>Evening</li>
</ul>
</div>
</template>

<script>
import { ref } from 'vue';

function getFirstListItemElement() {
const firstListItem = ref();
}
</script>
`,
output: `
<template>
<div>
<ul>
<li ref="firstListItem">Morning</li>
<li>Afternoon</li>
<li>Evening</li>
</ul>
</div>
</template>

<script>
import { ref } from 'vue';

function getFirstListItemElement() {
const firstListItem = useTemplateRef('firstListItem');
}
</script>
`,
errors: [
{
messageId: 'preferUseTemplateRef',
line: 16,
column: 33
}
]
}
]
})
Loading