index.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <template>
  2. <view :class="classes" ref="collapseDom">
  3. <slot></slot>
  4. </view>
  5. </template>
  6. <script lang="ts">
  7. import { computed, getCurrentInstance, onMounted, provide, ref, watch } from 'vue';
  8. import { createComponent } from '@/packages/utils/create';
  9. const { create, componentName } = createComponent('collapse');
  10. export default create({
  11. props: {
  12. modelValue: {
  13. type: [String, Number, Array],
  14. default: () => []
  15. },
  16. accordion: {
  17. type: Boolean,
  18. default: false
  19. }
  20. },
  21. emits: ['update:modelValue', 'change'],
  22. setup(props, { emit }) {
  23. const collapseDom: any = ref(null);
  24. const collapseChldren: any = ref([]);
  25. const classes = computed(() => {
  26. const prefixCls = componentName;
  27. return {
  28. [prefixCls]: true
  29. };
  30. });
  31. watch(
  32. () => props.modelValue,
  33. (newval: number | string | any) => {
  34. let doms: any = collapseChldren.value;
  35. Array.from(doms).forEach((item: any) => {
  36. if (typeof newval == 'number' || typeof newval == 'string') {
  37. item.changeOpen(newval == item.name ? true : false);
  38. } else if (Object.values(newval) instanceof Array) {
  39. const isOpen = newval.indexOf(Number(item.name)) > -1 || newval.indexOf(String(item.name)) > -1;
  40. item.changeOpen(isOpen);
  41. }
  42. item.animation();
  43. });
  44. }
  45. );
  46. onMounted(() => {
  47. collapseChldren.value = (getCurrentInstance() as any).provides.collapseParent.children || [];
  48. });
  49. const changeVal = (val: string | number | Array<string | number>) => {
  50. emit('update:modelValue', val);
  51. emit('change', val);
  52. };
  53. const changeValAry = (name: string) => {
  54. const activeItem: any = props.modelValue instanceof Object ? Object.values(props.modelValue) : props.modelValue;
  55. let index = -1;
  56. activeItem.forEach((item: string | number, idx: number) => {
  57. if (String(item) == String(name)) {
  58. index = idx;
  59. }
  60. });
  61. index > -1 ? activeItem.splice(index, 1) : activeItem.push(name);
  62. changeVal(activeItem);
  63. };
  64. const isExpanded = (name: string | number | Array<string | number>) => {
  65. const { accordion, modelValue } = props;
  66. if (accordion) {
  67. return typeof modelValue === 'number' || typeof modelValue === 'string' ? modelValue == name : false;
  68. }
  69. };
  70. provide('collapseParent', {
  71. children: [],
  72. props,
  73. changeValAry,
  74. changeVal,
  75. isExpanded
  76. });
  77. return { collapseDom, classes };
  78. }
  79. });
  80. </script>