index.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { VantComponent } from '../common/component';
  2. const nextTick = () => new Promise((resolve) => setTimeout(resolve, 20));
  3. VantComponent({
  4. classes: ['title-class', 'content-class'],
  5. relation: {
  6. name: 'collapse',
  7. type: 'ancestor',
  8. current: 'collapse-item',
  9. },
  10. props: {
  11. name: null,
  12. title: null,
  13. value: null,
  14. icon: String,
  15. label: String,
  16. disabled: Boolean,
  17. clickable: Boolean,
  18. border: {
  19. type: Boolean,
  20. value: true,
  21. },
  22. isLink: {
  23. type: Boolean,
  24. value: true,
  25. },
  26. },
  27. data: {
  28. contentHeight: 0,
  29. expanded: false,
  30. transition: false,
  31. },
  32. mounted() {
  33. this.updateExpanded()
  34. .then(nextTick)
  35. .then(() => {
  36. const data = { transition: true };
  37. if (this.data.expanded) {
  38. data.contentHeight = 'auto';
  39. }
  40. this.setData(data);
  41. });
  42. },
  43. methods: {
  44. updateExpanded() {
  45. if (!this.parent) {
  46. return Promise.resolve();
  47. }
  48. const { value, accordion } = this.parent.data;
  49. const { children = [] } = this.parent;
  50. const { name } = this.data;
  51. const index = children.indexOf(this);
  52. const currentName = name == null ? index : name;
  53. const expanded = accordion
  54. ? value === currentName
  55. : (value || []).some((name) => name === currentName);
  56. const stack = [];
  57. if (expanded !== this.data.expanded) {
  58. stack.push(this.updateStyle(expanded));
  59. }
  60. stack.push(this.set({ index, expanded }));
  61. return Promise.all(stack);
  62. },
  63. updateStyle(expanded) {
  64. return this.getRect('.van-collapse-item__content')
  65. .then((rect) => rect.height)
  66. .then((height) => {
  67. if (expanded) {
  68. return this.set({
  69. contentHeight: height ? `${height}px` : 'auto',
  70. });
  71. }
  72. return this.set({ contentHeight: `${height}px` })
  73. .then(nextTick)
  74. .then(() => this.set({ contentHeight: 0 }));
  75. });
  76. },
  77. onClick() {
  78. if (this.data.disabled) {
  79. return;
  80. }
  81. const { name, expanded } = this.data;
  82. const index = this.parent.children.indexOf(this);
  83. const currentName = name == null ? index : name;
  84. this.parent.switch(currentName, !expanded);
  85. },
  86. onTransitionEnd() {
  87. if (this.data.expanded) {
  88. this.setData({
  89. contentHeight: 'auto',
  90. });
  91. }
  92. },
  93. },
  94. });