Skip to content

fix(require-explicit-emits): detect template emits #2350

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

Merged
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
27 changes: 26 additions & 1 deletion lib/rules/require-explicit-emits.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,22 @@ function getNameParamNode(node) {
return null
}

/**
* Check if the given name matches defineEmitsNode variable name
* @param {string} name
* @param {CallExpression | undefined} defineEmitsNode
* @returns {boolean}
*/
function isEmitVariableName(name, defineEmitsNode) {
const node = defineEmitsNode?.parent

if (node?.type === 'VariableDeclarator' && node.id.type === 'Identifier') {
return name === node.id.name
}

return false
}

module.exports = {
meta: {
type: 'suggestion',
Expand Down Expand Up @@ -251,7 +267,16 @@ module.exports = {
if (!vueTemplateDefineData) {
return
}
if (callee.type === 'Identifier' && callee.name === '$emit') {

// e.g. $emit() / emit() in template
if (
callee.type === 'Identifier' &&
(callee.name === '$emit' ||
isEmitVariableName(
callee.name,
vueTemplateDefineData.defineEmits
))
) {
verifyEmit(
vueTemplateDefineData.emits,
vueTemplateDefineData.props,
Expand Down
32 changes: 32 additions & 0 deletions tests/lib/rules/require-explicit-emits.js
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,19 @@ tester.run('require-explicit-emits', rule, {
`,
parserOptions: { parser: require.resolve('@typescript-eslint/parser') }
},
{
filename: 'test.vue',
code: `
<template>
<div @click="emit('foo')"/>
<div @click="emit('bar')"/>
</template>
<script setup lang="ts">
const emit = defineEmits<(e: 'foo' | 'bar') => void>()
</script>
`,
parserOptions: { parser: require.resolve('@typescript-eslint/parser') }
},

// unknown emits definition
{
Expand Down Expand Up @@ -1983,6 +1996,25 @@ emits: {'foo': null}
}
],
...getTypeScriptFixtureTestOptions()
},
{
filename: 'test.vue',
code: `
<template>
<div @click="emit('bar')"/>
</template>
<script setup lang="ts">
const emit = defineEmits<(e: 'foo') => void>()
</script>
`,
parserOptions: { parser: require.resolve('@typescript-eslint/parser') },
errors: [
{
message:
'The "bar" event has been triggered but not declared on `defineEmits`.',
line: 3
}
]
}
]
})