vue2/src/directives/if.js

52 lines
1.1 KiB
JavaScript
Raw Normal View History

2014-08-17 06:06:37 +08:00
var _ = require('../util')
2014-08-18 03:36:13 +08:00
var templateParser = require('../parse/template')
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__) {
this.ref = document.createComment('v-if')
2014-08-21 11:00:27 +08:00
_.replace(el, this.ref)
2014-08-18 03:36:13 +08:00
this.inserted = false
if (el.tagName === 'TEMPLATE') {
2014-09-18 00:35:13 +08:00
this.el = templateParser.parse(el, 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) {
if (!this.inserted) {
if (!this.childVM) {
2014-08-30 22:54:06 +08:00
this.childVM = this.vm.$addChild({
el: this.el,
inherit: true,
2014-08-30 22:54:06 +08:00
_anonymous: true
})
2014-08-18 03:36:13 +08:00
}
this.childVM.$before(this.ref)
this.inserted = true
}
} else {
if (this.inserted) {
this.childVM.$remove()
this.inserted = false
}
}
},
2014-08-17 06:06:37 +08:00
unbind: function () {
2014-08-18 03:36:13 +08:00
if (this.childVM) {
this.childVM.$destroy()
}
2014-08-17 06:06:37 +08:00
}
2014-08-18 02:13:52 +08:00
2014-08-17 06:06:37 +08:00
}