feat(compiler-vapor): support v-for without prefixIdentifiers (#259)

Co-authored-by: 三咲智子 Kevin Deng <sxzz@sxzz.moe>
This commit is contained in:
zhiyuanzmj 2024-07-03 00:19:40 +08:00 committed by GitHub
parent 5eb43b08b2
commit b44ca85cb1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 38 additions and 6 deletions

View File

@ -30,6 +30,20 @@ export function render(_ctx) {
}" }"
`; `;
exports[`compiler: v-for > function params w/ prefixIdentifiers: false 1`] = `
"import { renderEffect as _renderEffect, setText as _setText, createFor as _createFor, template as _template } from 'vue/vapor';
const t0 = _template("<div></div>")
export function render(_ctx) {
const n0 = _createFor(() => (items), ([item, __, k]) => {
const n2 = t0()
_renderEffect(() => _setText(n2, item))
return n2
}, (item, __, k) => (k))
return n0
}"
`;
exports[`compiler: v-for > multi effect 1`] = ` exports[`compiler: v-for > multi effect 1`] = `
"import { renderEffect as _renderEffect, setDynamicProp as _setDynamicProp, createFor as _createFor, template as _template } from 'vue/vapor'; "import { renderEffect as _renderEffect, setDynamicProp as _setDynamicProp, createFor as _createFor, template as _template } from 'vue/vapor';
const t0 = _template("<div></div>") const t0 = _template("<div></div>")

View File

@ -223,4 +223,17 @@ describe('compiler: v-for', () => {
index: undefined, index: undefined,
}) })
}) })
test('function params w/ prefixIdentifiers: false', () => {
const { code } = compileWithVFor(
`<div v-for="(item, , k) of items" :key="k">{{ item }}</div>`,
{
prefixIdentifiers: false,
},
)
expect(code).contains(`_createFor(() => (items), ([item, __, k]) => {`)
expect(code).contain(`_setText(n2, item)`)
expect(code).matchSnapshot()
})
}) })

View File

@ -42,13 +42,18 @@ export function genFor(
} }
const [depth, exitScope] = context.enterScope() const [depth, exitScope] = context.enterScope()
const propsName = `_ctx${depth}` let propsName: string
const idMap: Record<string, string | null> = {} const idMap: Record<string, string | null> = {}
Array.from(idsOfValue).forEach( if (context.options.prefixIdentifiers) {
(id, idIndex) => (idMap[id] = `${propsName}[${idIndex}]`), propsName = `_ctx${depth}`
) Array.from(idsOfValue).forEach(
if (rawKey) idMap[rawKey] = `${propsName}[${idsOfValue.size}]` (id, idIndex) => (idMap[id] = `${propsName}[${idIndex}]`),
if (rawIndex) idMap[rawIndex] = `${propsName}[${idsOfValue.size + 1}]` )
if (rawKey) idMap[rawKey] = `${propsName}[${idsOfValue.size}]`
if (rawIndex) idMap[rawIndex] = `${propsName}[${idsOfValue.size + 1}]`
} else {
propsName = `[${[rawValue || ((rawKey || rawIndex) && '_'), rawKey || (rawIndex && '__'), rawIndex].filter(Boolean).join(', ')}]`
}
let blockFn = context.withId( let blockFn = context.withId(
() => genBlock(render, context, [propsName]), () => genBlock(render, context, [propsName]),