Skip to content

Add autofix to vue/prefer-use-template-ref #2632

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

Open
wants to merge 9 commits 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
5 changes: 5 additions & 0 deletions .changeset/cool-cycles-lick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"eslint-plugin-vue": minor
---

Added autofix to [vue/prefer-use-template-ref](https://eslint.vuejs.org/rules/prefer-use-template-ref.html).
2 changes: 1 addition & 1 deletion docs/rules/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ For example:
| [vue/prefer-prop-type-boolean-first] | enforce `Boolean` comes first in component prop types | :bulb: | :warning: |
| [vue/prefer-separate-static-class] | require static class names in template to be in a separate `class` attribute | :wrench: | :hammer: |
| [vue/prefer-true-attribute-shorthand] | require shorthand form attribute when `v-bind` value is `true` | :bulb: | :hammer: |
| [vue/prefer-use-template-ref] | require using `useTemplateRef` instead of `ref`/`shallowRef` for template refs | | :hammer: |
| [vue/prefer-use-template-ref] | require using `useTemplateRef` instead of `ref`/`shallowRef` for template refs | :wrench: | :hammer: |
| [vue/require-default-export] | require components to be the default export | | :warning: |
| [vue/require-direct-export] | require the component to be directly exported | | :hammer: |
| [vue/require-emit-validator] | require type definitions in emits | :bulb: | :hammer: |
Expand Down
6 changes: 4 additions & 2 deletions docs/rules/prefer-use-template-ref.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ since: v9.31.0

> require using `useTemplateRef` instead of `ref`/`shallowRef` for template refs

- :wrench: The `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fix-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
the [`useTemplateRef()`](https://vuejs.org/guide/essentials/template-refs.html#accessing-the-refs) API.

This rule enforces using the new `useTemplateRef` function instead of `ref`/`shallowRef` for template refs.

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

```vue
<template>
Expand Down Expand Up @@ -45,7 +47,7 @@ This rule enforces using the new `useTemplateRef` function instead of `ref`/`sha
This rule skips `ref` template function refs as these should be used to allow custom implementation of storing `ref`. If you prefer
`useTemplateRef`, you have to change the value of the template `ref` to a string.

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

```vue
<template>
Expand Down
91 changes: 89 additions & 2 deletions lib/rules/prefer-use-template-ref.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const utils = require('../utils')

/**
* @typedef ScriptRef
* @type {{node: Expression, ref: string}}
* @type {{node: Expression, ref: string, typeArguments?: string[]}}
*/

/**
Expand All @@ -20,7 +20,15 @@ function convertDeclaratorToScriptRef(declarator) {
// @ts-ignore
node: declarator.init,
// @ts-ignore
ref: declarator.id.name
ref: declarator.id.name,
// @ts-ignore
...(declarator.init?.typeArguments && {
// @ts-ignore
typeArguments: declarator.init.typeArguments.params.map(
// @ts-ignore
(param) => param.typeName.name
)
})
}
}

Expand All @@ -44,6 +52,58 @@ function getScriptRefsFromSetupFunction(body) {
return refDeclarators.map(convertDeclaratorToScriptRef)
}

/** @param node {Statement | ModuleDeclaration} */
function createIndent(node) {
const indentSize = node.loc.start.column

return ' '.repeat(indentSize)
}

/**
* @param context {RuleContext}
* @param fixer {RuleFixer}
* */
function addUseTemplateRefImport(context, fixer) {
const sourceCode = context.getSourceCode()

if (!sourceCode) {
return
}

const body = sourceCode.ast.body
const imports = body.filter((node) => node.type === 'ImportDeclaration')

const vueDestructuredImport = imports.find(
(importStatement) =>
importStatement.source.value === 'vue' &&
importStatement.specifiers.some(
(specifier) => specifier.type === 'ImportSpecifier'
)
)

if (vueDestructuredImport) {
const importSpecifiers = vueDestructuredImport.specifiers
const lastImportSpecifier = importSpecifiers[importSpecifiers.length - 1]

// @ts-ignore
return fixer.insertTextAfter(lastImportSpecifier, `, useTemplateRef`)
}

const importStatement = "import { useTemplateRef } from 'vue';"
const lastImport = imports[imports.length - 1]

if (lastImport) {
const indent = createIndent(lastImport)

return fixer.insertTextAfter(lastImport, `\n${indent}${importStatement}`)
}

const firstNode = body[0]
const indent = createIndent(firstNode)

return fixer.insertTextBefore(firstNode, `${importStatement}\n${indent}`)
}

/** @type {import("eslint").Rule.RuleModule} */
module.exports = {
meta: {
Expand All @@ -54,6 +114,7 @@ module.exports = {
categories: undefined,
url: 'https://eslint.vuejs.org/rules/prefer-use-template-ref.html'
},
fixable: 'code',
schema: [],
messages: {
preferUseTemplateRef: "Replace '{{name}}' with 'useTemplateRef'."
Expand Down Expand Up @@ -94,6 +155,8 @@ module.exports = {
}),
{
'Program:exit'() {
let missingImportChecked = false

for (const templateRef of templateRefs) {
const scriptRef = scriptRefs.find(
(scriptRef) => scriptRef.ref === templateRef
Expand All @@ -109,6 +172,30 @@ module.exports = {
data: {
// @ts-ignore
name: scriptRef.node?.callee?.name
},
fix(fixer) {
const typeArgumentsString = scriptRef.typeArguments
? `<${scriptRef.typeArguments.join(', ')}>`
: ''
const replaceFunctionFix = fixer.replaceText(
scriptRef.node,
`useTemplateRef${typeArgumentsString}('${scriptRef.ref}')`
)

if (!missingImportChecked) {
missingImportChecked = true
Copy link
Member

Choose a reason for hiding this comment

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

What is this flag for?
Perhaps to avoid autofix conflicts?
If so, ESLint's autofixes avoid conflicts as much as possible by core, so there's no need to handle that in the rules.


const missingImportFix = addUseTemplateRefImport(
context,
fixer
)

if (missingImportFix) {
return [replaceFunctionFix, missingImportFix]
}
}

return replaceFunctionFix
}
})
}
Expand Down
Loading
Loading