Skip to content

fix(compiler-sfc): add error handling for defineModel() without variable assignment #13352

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
6 changes: 3 additions & 3 deletions packages/compiler-sfc/__tests__/compileScript.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -980,7 +980,7 @@ describe('SFC compile <script setup>', () => {
expect(() =>
compile(`<script setup>
let bar = 1
defineModel({
const model = defineModel({
default: () => bar
})
</script>`),
Expand All @@ -990,7 +990,7 @@ describe('SFC compile <script setup>', () => {
expect(() =>
compile(`<script setup>
const bar = 1
defineModel({
const model = defineModel({
default: () => bar
})
</script>`),
Expand All @@ -1000,7 +1000,7 @@ describe('SFC compile <script setup>', () => {
expect(() =>
compile(`<script setup>
let bar = 1
defineModel({
const model = defineModel({
get: () => bar,
set: () => bar
})
Expand Down
12 changes: 12 additions & 0 deletions packages/compiler-sfc/__tests__/compileScript/defineModel.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,4 +269,16 @@ describe('defineModel()', () => {
modelValue: BindingTypes.SETUP_REF,
})
})

test('error when defineModel is not assigned to a variable', () => {
expect(() =>
compile(`
<script setup>
defineModel()
</script>
`),
).toThrow(
'defineModel() must be assigned to a variable. For example: const model = defineModel()',
)
})
})
7 changes: 7 additions & 0 deletions packages/compiler-sfc/src/script/defineModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ export function processDefineModel(
return false
}

if (!declId) {
ctx.error(
'defineModel() must be assigned to a variable. For example: const model = defineModel()',
node,
)
}

ctx.hasDefineModelCall = true

const type =
Expand Down