Skip to content

Commit

Permalink
fix(language-core): generate condition guards for model events (#5225)
Browse files Browse the repository at this point in the history
  • Loading branch information
KazariEX authored Mar 1, 2025
1 parent e334a2e commit 5ae4b38
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 6 deletions.
5 changes: 5 additions & 0 deletions packages/language-core/lib/codegen/template/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,11 @@ export function createTemplateCodegenContext(options: Pick<TemplateCodegenOption
yield endOfLine;
}
},
generateConditionGuards: function* () {
for (const condition of blockConditions) {
yield `if (!${condition}) return${endOfLine}`;
}
},
ignoreError: function* (): Generator<Code> {
if (!ignoredError) {
ignoredError = true;
Expand Down
11 changes: 5 additions & 6 deletions packages/language-core/lib/codegen/template/elementEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,9 @@ export function* generateEventExpression(
if (_isCompoundExpression) {
yield `(...[$event]) => {${newLine}`;
ctx.addLocalVariable('$event');

yield* ctx.generateConditionGuards();
prefix = ``;
suffix = ``;
for (const blockCondition of ctx.blockConditions) {
prefix += `if (!${blockCondition}) return${endOfLine}`;
}
}

yield* generateInterpolation(
Expand Down Expand Up @@ -178,7 +175,8 @@ export function* generateModelEventExpression(
prop: CompilerDOM.DirectiveNode
): Generator<Code> {
if (prop.exp?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
yield `(...[$event]) => (`;
yield `(...[$event]) => {${newLine}`;
yield* ctx.generateConditionGuards();
yield* generateInterpolation(
options,
ctx,
Expand All @@ -188,7 +186,8 @@ export function* generateModelEventExpression(
prop.exp.loc.start.offset,
prop.exp.loc
);
yield ` = $event)`;
yield ` = $event${endOfLine}`;
yield `}`;
}
else {
yield `() => {}`;
Expand Down
1 change: 1 addition & 0 deletions test-workspace/tsc/passedFixtures/vue2/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"../vue3/#4822",
"../vue3/#4826",
"../vue3/#4828",
"../vue3/#5225",
"../vue3/attrs",
"../vue3/components",
"../vue3/defineEmits",
Expand Down
3 changes: 3 additions & 0 deletions test-workspace/tsc/passedFixtures/vue3/#5225/comp.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<script setup lang="ts">
defineModel<number>({ required: true });
</script>
13 changes: 13 additions & 0 deletions test-workspace/tsc/passedFixtures/vue3/#5225/main.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script setup lang="ts">
import Comp from './comp.vue';
let foo!: {
bar?: number;
};
</script>

<template>
<!-- @vue-expect-error -->
<Comp v-model="foo.bar" />
<Comp v-if="foo.bar" v-model="foo.bar" />
</template>

0 comments on commit 5ae4b38

Please sign in to comment.