Skip to content

Commit

Permalink
refactor: Collapse use setup
Browse files Browse the repository at this point in the history
  • Loading branch information
wxsms committed Nov 22, 2021
1 parent 8833c83 commit 5b39e02
Showing 1 changed file with 44 additions and 55 deletions.
99 changes: 44 additions & 55 deletions src/components/collapse/Collapse.vue
Original file line number Diff line number Diff line change
@@ -1,85 +1,74 @@
<script lang="jsx">
<script>
import { addClass, removeClass } from '../../utils/dom.utils';
import { onMounted, ref, watchEffect, defineComponent, h } from 'vue';
const COLLAPSE = 'collapse';
const IN = 'in';
const COLLAPSING = 'collapsing';
export default {
export default defineComponent({
props: {
tag: {
type: String,
default: 'div',
},
modelValue: {
type: Boolean,
default: false,
},
transition: {
type: Number,
default: 350,
},
tag: { type: String, default: 'div' },
modelValue: { type: Boolean, default: false },
transition: { type: Number, default: 350 },
},
emits: ['show', 'shown', 'hide', 'hidden'],
data() {
return {
timeoutId: 0,
};
},
watch: {
modelValue(show) {
this.toggle(show);
},
},
mounted() {
const el = this.$el;
addClass(el, COLLAPSE);
if (this.modelValue) {
addClass(el, IN);
}
},
methods: {
toggle(show) {
clearTimeout(this.timeoutId);
const el = this.$el;
setup(props, { emit, slots }) {
const COLLAPSE = 'collapse';
const IN = 'in';
const COLLAPSING = 'collapsing';
let timeoutId = 0;
const element = ref(null);
function toggle(show) {
clearTimeout(timeoutId);
const el = element.value;
if (!el) {
return;
}
if (show) {
this.$emit('show');
emit('show');
removeClass(el, COLLAPSE);
el.style.height = 'auto';
const height = window.getComputedStyle(el).height;
el.style.height = null;
addClass(el, COLLAPSING);
el.offsetHeight; // force repaint
el.style.height = height;
this.timeoutId = setTimeout(() => {
timeoutId = setTimeout(() => {
removeClass(el, COLLAPSING);
addClass(el, COLLAPSE);
addClass(el, IN);
el.style.height = null;
this.timeoutId = 0;
this.$emit('shown');
}, this.transition);
timeoutId = 0;
emit('shown');
}, props.transition);
} else {
this.$emit('hide');
emit('hide');
el.style.height = window.getComputedStyle(el).height;
removeClass(el, IN);
removeClass(el, COLLAPSE);
el.offsetHeight;
el.style.height = null;
addClass(el, COLLAPSING);
this.timeoutId = setTimeout(() => {
timeoutId = setTimeout(() => {
addClass(el, COLLAPSE);
removeClass(el, COLLAPSING);
el.style.height = null;
this.timeoutId = 0;
this.$emit('hidden');
}, this.transition);
timeoutId = 0;
emit('hidden');
}, props.transition);
}
},
},
render() {
const Tag = this.tag;
return <Tag>{this.$slots.default?.()}</Tag>;
}
watchEffect(() => {
toggle(props.modelValue);
});
onMounted(() => {
addClass(element.value, COLLAPSE);
if (props.modelValue) {
addClass(element.value, IN);
}
});
return () => h(props.tag, { ref: element }, slots.default?.());
},
};
});
</script>

0 comments on commit 5b39e02

Please sign in to comment.