|
| 1 | +export const props = { |
| 2 | + tag: { |
| 3 | + type: String, |
| 4 | + default: 'div' |
| 5 | + }, |
| 6 | + duration: { |
| 7 | + type: Number, |
| 8 | + default: 400 |
| 9 | + }, |
| 10 | + transition: { |
| 11 | + type: String, |
| 12 | + default: 'ease-in-out' |
| 13 | + }, |
| 14 | + show: Boolean, |
| 15 | + navbar: Boolean |
| 16 | +} |
| 17 | + |
| 18 | +export default { |
| 19 | + name: 'CCollapse', |
| 20 | + props, |
| 21 | + data () { |
| 22 | + return { |
| 23 | + collapsing: false, |
| 24 | + heightWatcher: null |
| 25 | + } |
| 26 | + }, |
| 27 | + watch: { |
| 28 | + show (val) { |
| 29 | + if(this.collapsing){ |
| 30 | + this.turn() |
| 31 | + const height = Number(this.collapsing.slice(0,-2)) |
| 32 | + const current = this.$el.offsetHeight |
| 33 | + const time = val ? (height - current) / height : current / height |
| 34 | + this.setFinishTimer(this.duration * time) |
| 35 | + }else{ |
| 36 | + val ? this.toggle(true) : this.toggle(false) |
| 37 | + this.setFinishTimer(this.duration) |
| 38 | + } |
| 39 | + }, |
| 40 | + }, |
| 41 | + mounted () { |
| 42 | + this.$el.style.display = this.show ? '' : 'none' |
| 43 | + }, |
| 44 | + methods: { |
| 45 | + turn () { |
| 46 | + if(this.show) |
| 47 | + this.$el.style.height = this.collapsing |
| 48 | + else |
| 49 | + this.$el.style.height = 0 |
| 50 | + }, |
| 51 | + toggle (val) { |
| 52 | + this.$el.style.display = '' |
| 53 | + this.collapsing = this.$el.scrollHeight + 'px' |
| 54 | + this.$el.style.height = val ? 0 : this.$el.scrollHeight + 'px' |
| 55 | + this.$el.style.overflow = 'hidden' |
| 56 | + this.$el.style.transition = `all ${this.duration}ms ${this.transition}` |
| 57 | + const self = this |
| 58 | + setTimeout(() => { self.$el.style.height = val ? this.collapsing : 0 }, 0) |
| 59 | + }, |
| 60 | + setFinishTimer (duration) { |
| 61 | + clearTimeout(this.heightWatcher) |
| 62 | + const self = this |
| 63 | + this.heightWatcher = setTimeout(() => { |
| 64 | + self.collapsing = false |
| 65 | + self.$el.style.display = self.show ? '' : 'none' |
| 66 | + self.$el.style.height = '' |
| 67 | + self.$el.style.overflow = '' |
| 68 | + self.$el.style.transition = '' |
| 69 | + this.$emit('finish', self.show) |
| 70 | + }, duration) |
| 71 | + } |
| 72 | + }, |
| 73 | + render (h) { |
| 74 | + return h( |
| 75 | + this.tag, |
| 76 | + { |
| 77 | + class: { 'navbar-collapse': this.navbar } |
| 78 | + }, |
| 79 | + [ this.$slots.default ] |
| 80 | + ) |
| 81 | + } |
| 82 | +} |
0 commit comments