vue2/src/directives/if.js

68 lines
1.6 KiB
JavaScript

var _ = require('../util')
var compile = require('../compile/compile')
var templateParser = require('../parse/template')
var transition = require('../transition')
module.exports = {
bind: function () {
var el = this.el
if (!el.__vue__) {
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
)
} else {
this.invalid = true
_.warn(
'v-if="' + this.expression + '" cannot be ' +
'used on an already mounted instance.'
)
}
},
update: function (value) {
if (this.invalid) return
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
var frag = templateParser.clone(this.template)
var decompile = this.linker(vm, frag)
this.decompile = function () {
decompile()
transition.blockRemove(this.start, this.end, vm)
}
transition.blockAppend(frag, this.end, vm)
},
teardown: function () {
if (this.decompile) {
this.decompile()
this.decompile = null
}
}
}