fix(sfc): ensure consistent dev/prod behavior for non-reactive variables declared in `<script setup>`

fix #5655
This commit is contained in:
Evan You 2022-11-10 17:02:45 +08:00
parent f73925d76a
commit 5a3d45ae29
6 changed files with 19 additions and 7 deletions

View File

@ -1280,7 +1280,7 @@ export default {
function c() {}
class d {}
return { aa, bb, cc, dd, a, b, c, d, xx, x }
return { get aa() { return aa }, bb, cc, dd, get a() { return a }, b, c, d, xx, x }
}
}"

View File

@ -15,7 +15,7 @@ export default {
let c = () => {}
let d
return { foo, a, b, c, d, ref, shallowRef }
return { foo, a, b, get c() { return c }, get d() { return d }, ref, shallowRef }
}
}"
@ -36,7 +36,7 @@ export default {
let c = () => {}
let d
return { foo, a, b, c, d }
return { foo, a, b, get c() { return c }, get d() { return d } }
}
}"

View File

@ -84,7 +84,7 @@ _useCssVars(_ctx => ({
let b = 200
let foo = 300
return { a, b, foo }
return { get a() { return a }, get b() { return b }, get foo() { return foo } }
}
}"

View File

@ -20,7 +20,9 @@ describe('SFC compile <script setup>', () => {
class dd {}
</script>
`)
expect(content).toMatch('return { aa, bb, cc, dd, a, b, c, d, xx, x }')
expect(content).toMatch(
'return { get aa() { return aa }, bb, cc, dd, get a() { return a }, b, c, d, xx, x }'
)
expect(bindings).toStrictEqual({
x: BindingTypes.SETUP_MAYBE_REF,
a: BindingTypes.SETUP_LET,

View File

@ -32,7 +32,9 @@ describe('sfc ref transform', () => {
// normal declarations left untouched
expect(content).toMatch(`let c = () => {}`)
expect(content).toMatch(`let d`)
expect(content).toMatch(`return { foo, a, b, c, d, ref, shallowRef }`)
expect(content).toMatch(
`return { foo, a, b, get c() { return c }, get d() { return d }, ref, shallowRef }`
)
assertCode(content)
expect(bindings).toStrictEqual({
foo: BindingTypes.SETUP_REF,

View File

@ -1484,7 +1484,15 @@ export function compileScript(
allBindings[key] = true
}
}
returned = `{ ${Object.keys(allBindings).join(', ')} }`
returned = `{ `
for (const key in allBindings) {
if (bindingMetadata[key] === BindingTypes.SETUP_LET) {
returned += `get ${key}() { return ${key} }, `
} else {
returned += `${key}, `
}
}
returned = returned.replace(/, $/, '') + ` }`
} else {
// inline mode
if (sfc.template && !sfc.template.src) {