Skip to content

Commit

Permalink
fix(compiler-sfc): properly analyze destructured bindings with dynami…
Browse files Browse the repository at this point in the history
…c keys

fix #4540
  • Loading branch information
yyx990803 committed Sep 9, 2021
1 parent 781d2d4 commit a6e5f82
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 13 deletions.
Expand Up @@ -96,6 +96,19 @@ export default /*#__PURE__*/ Object.assign(__default__, {
})"
`;
exports[`SFC compile <script setup> binding analysis for destructur 1`] = `
"export default {
setup(__props, { expose }) {
expose()
const { foo, b: bar, ['x' + 'y']: baz, x: { y, zz: { z }}} = {}
return { foo, bar, baz, y, z }
}
}"
`;
exports[`SFC compile <script setup> defineEmits() 1`] = `
"export default {
emits: ['foo', 'bar'],
Expand Down
17 changes: 17 additions & 0 deletions packages/compiler-sfc/__tests__/compileScript.spec.ts
Expand Up @@ -36,6 +36,23 @@ describe('SFC compile <script setup>', () => {
assertCode(content)
})

test('binding analysis for destructur', () => {
const { content, bindings } = compile(`
<script setup>
const { foo, b: bar, ['x' + 'y']: baz, x: { y, zz: { z }}} = {}
</script>
`)
expect(content).toMatch('return { foo, bar, baz, y, z }')
expect(bindings).toStrictEqual({
foo: BindingTypes.SETUP_MAYBE_REF,
bar: BindingTypes.SETUP_MAYBE_REF,
baz: BindingTypes.SETUP_MAYBE_REF,
y: BindingTypes.SETUP_MAYBE_REF,
z: BindingTypes.SETUP_MAYBE_REF
})
assertCode(content)
})

test('defineProps()', () => {
const { content, bindings } = compile(`
<script setup>
Expand Down
23 changes: 10 additions & 13 deletions packages/compiler-sfc/src/compileScript.ts
Expand Up @@ -1347,19 +1347,16 @@ function walkObjectPattern(
) {
for (const p of node.properties) {
if (p.type === 'ObjectProperty') {
// key can only be Identifier in ObjectPattern
if (p.key.type === 'Identifier') {
if (p.key === p.value) {
// const { x } = ...
const type = isDefineCall
? BindingTypes.SETUP_CONST
: isConst
? BindingTypes.SETUP_MAYBE_REF
: BindingTypes.SETUP_LET
registerBinding(bindings, p.key, type)
} else {
walkPattern(p.value, bindings, isConst, isDefineCall)
}
if (p.key.type === 'Identifier' && p.key === p.value) {
// shorthand: const { x } = ...
const type = isDefineCall
? BindingTypes.SETUP_CONST
: isConst
? BindingTypes.SETUP_MAYBE_REF
: BindingTypes.SETUP_LET
registerBinding(bindings, p.key, type)
} else {
walkPattern(p.value, bindings, isConst, isDefineCall)
}
} else {
// ...rest
Expand Down

0 comments on commit a6e5f82

Please sign in to comment.