Skip to content

Commit 430452e

Browse files
committed
support v-else (close vuejs#1290)
1 parent b6ad25b commit 430452e

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
@@ -487,7 +487,8 @@ function checkComponent (el, options, hasAttrs) {
487487
*/
488488

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

src/directives/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/if_spec.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,5 +391,23 @@ if (_.inBrowser) {
391391
expect(parentA).toBe(parentB)
392392
})
393393

394+
it('if + else', function (done) {
395+
var vm = new Vue({
396+
el: el,
397+
data: { test: false, a: 'A', b: 'B' },
398+
template: '<div v-if="test">{{a}}</div><div v-else>{{b}}</div>'
399+
})
400+
expect(el.textContent).toBe('B')
401+
vm.test = true
402+
_.nextTick(function () {
403+
expect(el.textContent).toBe('A')
404+
vm.test = false
405+
_.nextTick(function () {
406+
expect(el.textContent).toBe('B')
407+
done()
408+
})
409+
})
410+
})
411+
394412
})
395413
}

0 commit comments

Comments
 (0)