Skip to content

Commit aca2c2a

Browse files
soouupyyx990803
authored andcommitted
fix(compiler-core): avoid override user keys when injecting branch key (#630)
1 parent c71ca35 commit aca2c2a

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

packages/compiler-core/__tests__/transforms/__snapshots__/vIf.spec.ts.snap

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,17 @@ return function render() {
105105
}
106106
}"
107107
`;
108+
109+
exports[`compiler: v-if codegen v-if with key 1`] = `
110+
"const _Vue = Vue
111+
112+
return function render() {
113+
with (this) {
114+
const { openBlock: _openBlock, createVNode: _createVNode, createBlock: _createBlock, createCommentVNode: _createCommentVNode } = _Vue
115+
116+
return (_openBlock(), ok
117+
? _createBlock(\\"div\\", { key: \\"some-key\\" })
118+
: _createCommentVNode(\\"v-if\\", true))
119+
}
120+
}"
121+
`;

packages/compiler-core/__tests__/transforms/vIf.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,20 @@ describe('compiler: v-if', () => {
530530
)
531531
})
532532

533+
test('v-if with key', () => {
534+
const {
535+
root,
536+
node: { codegenNode }
537+
} = parseWithIfTransform(`<div v-if="ok" key="some-key"/>`)
538+
const branch1 = (codegenNode.expressions[1] as ConditionalExpression)
539+
.consequent as CallExpression
540+
expect(branch1.arguments).toMatchObject([
541+
`"div"`,
542+
createObjectMatcher({ key: 'some-key' })
543+
])
544+
expect(generate(root).code).toMatchSnapshot()
545+
})
546+
533547
test.todo('with comments')
534548
})
535549
})

packages/compiler-core/src/utils.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,18 @@ export function injectProp(
253253
}
254254
propsWithInjection = props
255255
} else if (props.type === NodeTypes.JS_OBJECT_EXPRESSION) {
256-
props.properties.unshift(prop)
256+
let alreadyExists = false
257+
// check existing key to avoid overriding user provided keys
258+
if (prop.key.type === NodeTypes.SIMPLE_EXPRESSION) {
259+
const propKeyName = prop.key.content
260+
alreadyExists = props.properties.some(p => (
261+
p.key.type === NodeTypes.SIMPLE_EXPRESSION &&
262+
p.key.content === propKeyName
263+
))
264+
}
265+
if (!alreadyExists) {
266+
props.properties.unshift(prop)
267+
}
257268
propsWithInjection = props
258269
} else {
259270
// single v-bind with expression, return a merged replacement

0 commit comments

Comments
 (0)