Skip to content

Commit 534e12d

Browse files
committed
support v-else (close #1290)
1 parent d4301c6 commit 534e12d

File tree

3 files changed

+41
-5
lines changed

3 files changed

+41
-5
lines changed

src/compiler/compile.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,8 @@ function checkComponent (el, options) {
488488
*/
489489

490490
function checkTerminalDirectives (el, options) {
491-
if (_.attr(el, 'pre') !== null) {
491+
if (_.attr(el, 'pre') !== null ||
492+
el.hasAttribute(config.prefix + 'else')) {
492493
return skip
493494
}
494495
var value, dirName

src/directives/public/if.js

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@ module.exports = {
88
bind: function () {
99
var el = this.el
1010
if (!el.__vue__) {
11+
// check else block
12+
var next = el.nextElementSibling
13+
if (next && _.attr(next, 'else') !== null) {
14+
_.remove(next)
15+
this.elseFactory = new FragmentFactory(this.vm, next)
16+
}
17+
// check main block
1118
this.anchor = _.createAnchor('v-if')
1219
_.replace(el, this.anchor)
1320
this.factory = new FragmentFactory(this.vm, el)
@@ -32,15 +39,25 @@ module.exports = {
3239
},
3340

3441
insert: function () {
42+
if (this.elseFrag) {
43+
this.elseFrag.remove()
44+
this.elseFrag.destroy()
45+
this.elseFrag = null
46+
}
3547
this.frag = this.factory.create(this._host, this._scope, this._frag)
3648
this.frag.before(this.anchor)
3749
},
3850

3951
remove: function () {
40-
if (!this.frag) return
41-
this.frag.remove()
42-
this.frag.destroy()
43-
this.frag = null
52+
if (this.frag) {
53+
this.frag.remove()
54+
this.frag.destroy()
55+
this.frag = null
56+
}
57+
if (this.elseFactory) {
58+
this.elseFrag = this.elseFactory.create(this._host, this._scope, this._frag)
59+
this.elseFrag.before(this.anchor)
60+
}
4461
},
4562

4663
unbind: function () {

test/unit/specs/directives/public/if_spec.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,5 +396,23 @@ if (_.inBrowser) {
396396
expect(parentA).toBe(parentB)
397397
})
398398

399+
it('if + else', function (done) {
400+
var vm = new Vue({
401+
el: el,
402+
data: { test: false, a: 'A', b: 'B' },
403+
template: '<div v-if="test">{{a}}</div><div v-else>{{b}}</div>'
404+
})
405+
expect(el.textContent).toBe('B')
406+
vm.test = true
407+
_.nextTick(function () {
408+
expect(el.textContent).toBe('A')
409+
vm.test = false
410+
_.nextTick(function () {
411+
expect(el.textContent).toBe('B')
412+
done()
413+
})
414+
})
415+
})
416+
399417
})
400418
}

0 commit comments

Comments
 (0)