Skip to content

Commit 5ae4b38

Browse files
authored
fix(language-core): generate condition guards for model events (#5225)
1 parent e334a2e commit 5ae4b38

File tree

5 files changed

+27
-6
lines changed

5 files changed

+27
-6
lines changed

packages/language-core/lib/codegen/template/context.ts

+5
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,11 @@ export function createTemplateCodegenContext(options: Pick<TemplateCodegenOption
242242
yield endOfLine;
243243
}
244244
},
245+
generateConditionGuards: function* () {
246+
for (const condition of blockConditions) {
247+
yield `if (!${condition}) return${endOfLine}`;
248+
}
249+
},
245250
ignoreError: function* (): Generator<Code> {
246251
if (!ignoredError) {
247252
ignoredError = true;

packages/language-core/lib/codegen/template/elementEvents.ts

+5-6
Original file line numberDiff line numberDiff line change
@@ -122,12 +122,9 @@ export function* generateEventExpression(
122122
if (_isCompoundExpression) {
123123
yield `(...[$event]) => {${newLine}`;
124124
ctx.addLocalVariable('$event');
125-
125+
yield* ctx.generateConditionGuards();
126126
prefix = ``;
127127
suffix = ``;
128-
for (const blockCondition of ctx.blockConditions) {
129-
prefix += `if (!${blockCondition}) return${endOfLine}`;
130-
}
131128
}
132129

133130
yield* generateInterpolation(
@@ -178,7 +175,8 @@ export function* generateModelEventExpression(
178175
prop: CompilerDOM.DirectiveNode
179176
): Generator<Code> {
180177
if (prop.exp?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
181-
yield `(...[$event]) => (`;
178+
yield `(...[$event]) => {${newLine}`;
179+
yield* ctx.generateConditionGuards();
182180
yield* generateInterpolation(
183181
options,
184182
ctx,
@@ -188,7 +186,8 @@ export function* generateModelEventExpression(
188186
prop.exp.loc.start.offset,
189187
prop.exp.loc
190188
);
191-
yield ` = $event)`;
189+
yield ` = $event${endOfLine}`;
190+
yield `}`;
192191
}
193192
else {
194193
yield `() => {}`;

test-workspace/tsc/passedFixtures/vue2/tsconfig.json

+1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
"../vue3/#4822",
3030
"../vue3/#4826",
3131
"../vue3/#4828",
32+
"../vue3/#5225",
3233
"../vue3/attrs",
3334
"../vue3/components",
3435
"../vue3/defineEmits",
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<script setup lang="ts">
2+
defineModel<number>({ required: true });
3+
</script>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<script setup lang="ts">
2+
import Comp from './comp.vue';
3+
4+
let foo!: {
5+
bar?: number;
6+
};
7+
</script>
8+
9+
<template>
10+
<!-- @vue-expect-error -->
11+
<Comp v-model="foo.bar" />
12+
<Comp v-if="foo.bar" v-model="foo.bar" />
13+
</template>

0 commit comments

Comments
 (0)