vue2/src/directives/if.js

68 lines
1.6 KiB
JavaScript
Raw Normal View History

2014-08-17 06:06:37 +08:00
var _ = require('../util')
var compile = require('../compile/compile')
2014-08-18 03:36:13 +08:00
var templateParser = require('../parse/template')
var transition = require('../transition')
2014-08-17 06:06:37 +08:00
module.exports = {
bind: function () {
2014-08-18 03:36:13 +08:00
var el = this.el
if (!el.__vue__) {
2014-10-21 13:38:19 +08:00
this.start = document.createComment('v-if-start')
this.end = document.createComment('v-if-end')
_.replace(el, this.end)
_.before(this.start, this.end)
if (el.tagName === 'TEMPLATE') {
this.template = templateParser.parse(el, true)
} else {
this.template = document.createDocumentFragment()
this.template.appendChild(el)
}
// compile the nested partial
this.linker = compile(
this.template,
this.vm.$options,
true
)
2014-08-18 03:36:13 +08:00
} else {
2014-08-28 06:59:38 +08:00
this.invalid = true
2014-08-18 03:36:13 +08:00
_.warn(
2014-08-28 06:59:38 +08:00
'v-if="' + this.expression + '" cannot be ' +
2014-08-18 03:36:13 +08:00
'used on an already mounted instance.'
)
}
2014-08-17 06:06:37 +08:00
},
2014-08-18 03:36:13 +08:00
update: function (value) {
2014-08-28 06:59:38 +08:00
if (this.invalid) return
2014-08-18 03:36:13 +08:00
if (value) {
this.insert()
} else {
this.teardown()
}
},
insert: function () {
// avoid duplicate inserts, since update() can be
// called with different truthy values
if (this.decompile) {
return
}
var vm = this.vm
2014-10-21 13:38:19 +08:00
var frag = templateParser.clone(this.template)
var decompile = this.linker(vm, frag)
this.decompile = function () {
decompile()
transition.blockRemove(this.start, this.end, vm)
2014-08-18 03:36:13 +08:00
}
2014-10-21 13:38:19 +08:00
transition.blockAppend(frag, this.end, vm)
2014-08-18 03:36:13 +08:00
},
teardown: function () {
if (this.decompile) {
this.decompile()
this.decompile = null
2014-08-18 03:36:13 +08:00
}
2014-08-17 06:06:37 +08:00
}
2014-08-18 02:13:52 +08:00
2014-08-17 06:06:37 +08:00
}