Skip to content

Commit cc0b0f0

Browse files
waynzhFloEdelmann
andauthored
fix(no-unused-emit-declarations): detect emits in templates (#2340)
Co-authored-by: Flo Edelmann <[email protected]>
1 parent 591c7af commit cc0b0f0

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed

lib/rules/no-unused-emit-declarations.js

+20
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,17 @@ function hasReferenceId(value, setupContext) {
5656
)
5757
}
5858

59+
/**
60+
* Check if the given name matches emitReferenceIds variable name
61+
* @param {string} name
62+
* @param {Set<Identifier>} emitReferenceIds
63+
* @returns {boolean}
64+
*/
65+
function isEmitVariableName(name, emitReferenceIds) {
66+
const emitVariable = emitReferenceIds.values().next().value.name
67+
return emitVariable === name
68+
}
69+
5970
module.exports = {
6071
meta: {
6172
type: 'suggestion',
@@ -191,6 +202,15 @@ module.exports = {
191202
}
192203

193204
const { contextReferenceIds, emitReferenceIds } = setupContext
205+
206+
// verify defineEmits variable in template
207+
if (
208+
callee.type === 'Identifier' &&
209+
isEmitVariableName(callee.name, emitReferenceIds)
210+
) {
211+
addEmitCall(node)
212+
}
213+
194214
// verify setup(props,{emit}) {emit()}
195215
addEmitCallByReference(callee, emitReferenceIds, node)
196216
if (emit && emit.name === 'emit') {

tests/lib/rules/no-unused-emit-declarations.js

+32-2
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,17 @@ tester.run('no-unused-emit-declarations', rule, {
9898
}
9999
`
100100
},
101+
{
102+
filename: 'test.vue',
103+
code: `
104+
<template>
105+
<button @click="emits('bar')">Bar</button>
106+
</template>
107+
<script setup>
108+
const emits = defineEmits(['bar'])
109+
</script>
110+
`
111+
},
101112
{
102113
filename: 'test.vue',
103114
code: `
@@ -237,7 +248,7 @@ tester.run('no-unused-emit-declarations', rule, {
237248
export default {
238249
emits: ['foo'],
239250
setup(_, context) {
240-
useCustomComposable({ emit: context.emit })
251+
useCustomComposable({ emit: context.emit })
241252
}
242253
}
243254
</script>
@@ -282,7 +293,7 @@ tester.run('no-unused-emit-declarations', rule, {
282293
export default {
283294
emits: ['foo'],
284295
setup(_, { emit }) {
285-
useCustomComposable({ emit: emit })
296+
useCustomComposable({ emit: emit })
286297
}
287298
}
288299
</script>
@@ -453,6 +464,25 @@ tester.run('no-unused-emit-declarations', rule, {
453464
}
454465
]
455466
},
467+
{
468+
filename: 'test.vue',
469+
code: `
470+
<template>
471+
<button @click="emit('bar')">Bar</button>
472+
</template>
473+
<script setup>
474+
const emit = defineEmits(['foo', 'bar'])
475+
</script>
476+
`,
477+
errors: [
478+
{
479+
messageId: 'unused',
480+
line: 6,
481+
column: 35,
482+
endColumn: 40
483+
}
484+
]
485+
},
456486
{
457487
filename: 'test.vue',
458488
code: `

0 commit comments

Comments
 (0)