Skip to content

Commit 4e575ea

Browse files
authored
Update vue/no-unused-refs rule to support setup() and <script setup> (#1556)
1 parent fed7f4e commit 4e575ea

File tree

2 files changed

+85
-15
lines changed

2 files changed

+85
-15
lines changed

Diff for: lib/rules/no-unused-refs.js

+54-15
Original file line numberDiff line numberDiff line change
@@ -180,25 +180,64 @@ module.exports = {
180180
reportUnusedRefs()
181181
}
182182
},
183-
{
184-
Identifier(id) {
185-
if (hasUnknown) {
186-
return
187-
}
188-
if (id.name !== '$refs') {
189-
return
183+
utils.compositingVisitors(
184+
utils.isScriptSetup(context)
185+
? {
186+
Program() {
187+
const globalScope =
188+
context.getSourceCode().scopeManager.globalScope
189+
if (!globalScope) {
190+
return
191+
}
192+
for (const variable of globalScope.variables) {
193+
if (variable.defs.length > 0) {
194+
usedRefs.add(variable.name)
195+
}
196+
}
197+
const moduleScope = globalScope.childScopes.find(
198+
(scope) => scope.type === 'module'
199+
)
200+
if (!moduleScope) {
201+
return
202+
}
203+
for (const variable of moduleScope.variables) {
204+
if (variable.defs.length > 0) {
205+
usedRefs.add(variable.name)
206+
}
207+
}
208+
}
209+
}
210+
: {},
211+
utils.defineVueVisitor(context, {
212+
onVueObjectEnter(node) {
213+
for (const prop of utils.iterateProperties(
214+
node,
215+
new Set(['setup'])
216+
)) {
217+
usedRefs.add(prop.name)
218+
}
190219
}
191-
/** @type {Identifier | MemberExpression} */
192-
let refsNode = id
193-
if (id.parent.type === 'MemberExpression') {
194-
if (id.parent.property === id) {
195-
// `this.$refs.foo`
196-
refsNode = id.parent
220+
}),
221+
{
222+
Identifier(id) {
223+
if (hasUnknown) {
224+
return
225+
}
226+
if (id.name !== '$refs') {
227+
return
197228
}
229+
/** @type {Identifier | MemberExpression} */
230+
let refsNode = id
231+
if (id.parent.type === 'MemberExpression') {
232+
if (id.parent.property === id) {
233+
// `this.$refs.foo`
234+
refsNode = id.parent
235+
}
236+
}
237+
extractUsedForPattern(refsNode)
198238
}
199-
extractUsedForPattern(refsNode)
200239
}
201-
}
240+
)
202241
)
203242
}
204243
}

Diff for: tests/lib/rules/no-unused-refs.js

+31
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,37 @@ tester.run('no-unused-refs', rule, {
284284
}
285285
</script>
286286
`
287+
},
288+
{
289+
filename: 'test.vue',
290+
code: `
291+
<template>
292+
<input ref="x" />
293+
</template>
294+
<script>
295+
import {ref} from 'vue'
296+
export default {
297+
setup() {
298+
const x = ref(null)
299+
return {
300+
x
301+
}
302+
}
303+
}
304+
</script>
305+
`
306+
},
307+
{
308+
filename: 'test.vue',
309+
code: `
310+
<template>
311+
<input ref="x" />
312+
</template>
313+
<script setup>
314+
import {ref} from 'vue'
315+
const x = ref(null)
316+
</script>
317+
`
287318
}
288319
],
289320

0 commit comments

Comments
 (0)