index.js 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { VantComponent } from '../common/component';
  2. const ITEM_HEIGHT = 44;
  3. VantComponent({
  4. classes: [
  5. 'main-item-class',
  6. 'content-item-class',
  7. 'main-active-class',
  8. 'content-active-class',
  9. 'main-disabled-class',
  10. 'content-disabled-class'
  11. ],
  12. props: {
  13. items: Array,
  14. mainActiveIndex: {
  15. type: Number,
  16. value: 0
  17. },
  18. activeId: {
  19. type: [Number, String, Array]
  20. },
  21. maxHeight: {
  22. type: Number,
  23. value: 300
  24. }
  25. },
  26. data: {
  27. subItems: [],
  28. mainHeight: 0,
  29. itemHeight: 0
  30. },
  31. watch: {
  32. items() {
  33. this.updateSubItems().then(() => {
  34. this.updateMainHeight();
  35. });
  36. },
  37. maxHeight() {
  38. this.updateItemHeight(this.data.subItems);
  39. this.updateMainHeight();
  40. },
  41. mainActiveIndex: 'updateSubItems'
  42. },
  43. methods: {
  44. // 当一个子项被选择时
  45. onSelectItem(event) {
  46. const { item } = event.currentTarget.dataset;
  47. if (!item.disabled) {
  48. this.$emit('click-item', item);
  49. }
  50. },
  51. // 当一个导航被点击时
  52. onClickNav(event) {
  53. const { index } = event.currentTarget.dataset;
  54. const item = this.data.items[index];
  55. if (!item.disabled) {
  56. this.$emit('click-nav', { index });
  57. }
  58. },
  59. // 更新子项列表
  60. updateSubItems() {
  61. const { items, mainActiveIndex } = this.data;
  62. const { children = [] } = items[mainActiveIndex] || {};
  63. this.updateItemHeight(children);
  64. return this.set({ subItems: children });
  65. },
  66. // 更新组件整体高度,根据最大高度和当前组件需要展示的高度来决定
  67. updateMainHeight() {
  68. const { items = [], subItems = [] } = this.data;
  69. const maxHeight = Math.max(items.length * ITEM_HEIGHT, subItems.length * ITEM_HEIGHT);
  70. this.set({ mainHeight: Math.min(maxHeight, this.data.maxHeight) });
  71. },
  72. // 更新子项列表高度,根据可展示的最大高度和当前子项列表的高度决定
  73. updateItemHeight(subItems) {
  74. const itemHeight = Math.min(subItems.length * ITEM_HEIGHT, this.data.maxHeight);
  75. return this.set({ itemHeight });
  76. }
  77. }
  78. });