index.js 2.9 KB

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