Skip to content

fix(compiler-vapor): properly cache variable with optional chaining #13519

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 1 commit into from
Jun 26, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,20 @@ export function render(_ctx) {
}"
`;

exports[`cache multiple access > optional chaining 1`] = `
"import { setProp as _setProp, renderEffect as _renderEffect, template as _template } from 'vue';
const t0 = _template("<div></div>", true)

export function render(_ctx) {
const n0 = t0()
_renderEffect(() => {
const _obj = _ctx.obj
_setProp(n0, "id", _obj?.foo + _obj?.bar)
})
return n0
}"
`;

exports[`cache multiple access > repeated expression in expressions 1`] = `
"import { setProp as _setProp, renderEffect as _renderEffect, template as _template } from 'vue';
const t0 = _template("<div></div>")
Expand Down
7 changes: 7 additions & 0 deletions packages/compiler-vapor/__tests__/transforms/vBind.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,13 @@ describe('cache multiple access', () => {
expect(code).contains('_setStyle(n0, {color: _color})')
})

test('optional chaining', () => {
const { code } = compileWithVBind(`<div :id="obj?.foo + obj?.bar"></div>`)
expect(code).matchSnapshot()
expect(code).contains('const _obj = _ctx.obj')
expect(code).contains('_setProp(n0, "id", _obj?.foo + _obj?.bar)')
})

test('not cache variable only used in property shorthand', () => {
const { code } = compileWithVBind(`
<div :style="{color}" />
Expand Down
1 change: 1 addition & 0 deletions packages/compiler-vapor/src/generators/expression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,7 @@ function extractMemberExpression(
case 'CallExpression': // foo[bar(baz)]
return `${extractMemberExpression(exp.callee, onIdentifier)}(${exp.arguments.map(arg => extractMemberExpression(arg, onIdentifier)).join(', ')})`
case 'MemberExpression': // foo[bar.baz]
case 'OptionalMemberExpression': // foo?.bar
const object = extractMemberExpression(exp.object, onIdentifier)
const prop = exp.computed
? `[${extractMemberExpression(exp.property, onIdentifier)}]`
Expand Down