Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/nine-zebras-rule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"eslint-plugin-vue": patch
---

Improved performance and type safety in `vue/prefer-use-template-ref`
52 changes: 20 additions & 32 deletions lib/rules/prefer-use-template-ref.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,40 +8,29 @@ const utils = require('../utils')

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

/**
* @param declarator {VariableDeclarator}
* @returns {ScriptRef}
* */
function convertDeclaratorToScriptRef(declarator) {
return {
// @ts-ignore
node: declarator.init,
// @ts-ignore
ref: declarator.id.name
}
}

/**
* @param body {(Statement | ModuleDeclaration)[]}
* @returns {ScriptRef[]}
* */
function getScriptRefsFromSetupFunction(body) {
/** @type {VariableDeclaration[]} */
const variableDeclarations = body.filter(
(child) => child.type === 'VariableDeclaration'
)
const variableDeclarators = variableDeclarations.map(
(declaration) => declaration.declarations[0]
)
const refDeclarators = variableDeclarators.filter((declarator) =>
// @ts-ignore
['ref', 'shallowRef'].includes(declarator.init?.callee?.name)
)
return body.flatMap((child) => {
if (child.type === 'VariableDeclaration') {
const declarator = child.declarations[0]

if (
declarator.init?.type === 'CallExpression' &&
declarator.init.callee?.type === 'Identifier' &&
declarator.id.type === 'Identifier' &&
['ref', 'shallowRef'].includes(declarator.init.callee.name)
)
return [[declarator.id.name, declarator.init]]
}

return refDeclarators.map(convertDeclaratorToScriptRef)
return []
})
}

/** @type {import("eslint").Rule.RuleModule} */
Expand Down Expand Up @@ -94,21 +83,20 @@ module.exports = {
}),
{
'Program:exit'() {
const scriptRefsMap = new Map(scriptRefs)

for (const templateRef of templateRefs) {
const scriptRef = scriptRefs.find(
(scriptRef) => scriptRef.ref === templateRef
)
const scriptRef = scriptRefsMap.get(templateRef)

if (!scriptRef) {
continue
}

context.report({
node: scriptRef.node,
node: scriptRef,
messageId: 'preferUseTemplateRef',
data: {
// @ts-ignore
name: scriptRef.node?.callee?.name
name: /** @type {Identifier} */ (scriptRef.callee).name
}
})
}
Expand Down
Loading