Skip to content

Commit de220a6

Browse files
committed
ignore text nodes between v-if conditions (fix vuejs#4533)
1 parent 84b7b82 commit de220a6

File tree

2 files changed

+31
-7
lines changed

2 files changed

+31
-7
lines changed

src/compiler/parser/index.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,23 @@ function processIfConditions (el, parent) {
352352
}
353353
}
354354

355+
function findPrevElement (children: Array<any>): ASTElement | void {
356+
let i = children.length
357+
while (i--) {
358+
if (children[i].type === 1) {
359+
return children[i]
360+
} else {
361+
if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') {
362+
warn(
363+
`text "${children[i].text.trim()}" between v-if and v-else(-if) ` +
364+
`will be ignored.`
365+
)
366+
}
367+
children.pop()
368+
}
369+
}
370+
}
371+
355372
function addIfCondition (el, condition) {
356373
if (!el.ifConditions) {
357374
el.ifConditions = []
@@ -503,13 +520,6 @@ function makeAttrsMap (attrs: Array<Object>): Object {
503520
return map
504521
}
505522

506-
function findPrevElement (children: Array<any>): ASTElement | void {
507-
let i = children.length
508-
while (i--) {
509-
if (children[i].tag) return children[i]
510-
}
511-
}
512-
513523
function isForbiddenTag (el): boolean {
514524
return (
515525
el.tag === 'style' ||

test/unit/modules/compiler/parser.spec.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,20 @@ describe('parser', () => {
8282
expect('Component template should contain exactly one root element:\n\n<div></div><div></div>').toHaveBeenWarned()
8383
})
8484

85+
it('remove text nodes between v-if conditions', () => {
86+
const ast = parse(`<div><div v-if="1"></div> <div v-else-if="2"></div> <div v-else></div> <span></span></div>`, baseOptions)
87+
expect(ast.children.length).toBe(3)
88+
expect(ast.children[0].tag).toBe('div')
89+
expect(ast.children[0].ifConditions.length).toBe(3)
90+
expect(ast.children[1].text).toBe(' ') // text
91+
expect(ast.children[2].tag).toBe('span')
92+
})
93+
94+
it('warn non whitespace text between v-if conditions', () => {
95+
parse(`<div><div v-if="1"></div> foo <div v-else></div></div>`, baseOptions)
96+
expect(`text "foo" between v-if and v-else(-if) will be ignored`).toHaveBeenWarned()
97+
})
98+
8599
it('not warn 2 root elements with v-if and v-else', () => {
86100
parse('<div v-if="1"></div><div v-else></div>', baseOptions)
87101
expect('Component template should contain exactly one root element')

0 commit comments

Comments
 (0)