if.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var _ = require('../../util')
  2. var FragmentFactory = require('../../fragment/factory')
  3. module.exports = {
  4. priority: 2000,
  5. bind: function () {
  6. var el = this.el
  7. if (!el.__vue__) {
  8. // check else block
  9. var next = el.nextElementSibling
  10. if (next && _.attr(next, 'v-else') !== null) {
  11. _.remove(next)
  12. this.elseFactory = new FragmentFactory(this.vm, next)
  13. }
  14. // check main block
  15. this.anchor = _.createAnchor('v-if')
  16. _.replace(el, this.anchor)
  17. this.factory = new FragmentFactory(this.vm, el)
  18. } else {
  19. process.env.NODE_ENV !== 'production' && _.warn(
  20. 'v-if="' + this.expression + '" cannot be ' +
  21. 'used on an instance root element.'
  22. )
  23. this.invalid = true
  24. }
  25. },
  26. update: function (value) {
  27. if (this.invalid) return
  28. if (value) {
  29. if (!this.frag) {
  30. this.insert()
  31. }
  32. } else {
  33. this.remove()
  34. }
  35. },
  36. insert: function () {
  37. if (this.elseFrag) {
  38. this.elseFrag.remove(true)
  39. this.elseFrag = null
  40. }
  41. this.frag = this.factory.create(this._host, this._scope, this._frag)
  42. this.frag.before(this.anchor)
  43. },
  44. remove: function () {
  45. if (this.frag) {
  46. this.frag.remove(true)
  47. this.frag = null
  48. }
  49. if (this.elseFactory) {
  50. this.elseFrag = this.elseFactory.create(this._host, this._scope, this._frag)
  51. this.elseFrag.before(this.anchor)
  52. }
  53. },
  54. unbind: function () {
  55. if (this.frag) {
  56. this.frag.destroy()
  57. }
  58. }
  59. }