layout-observer.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. export default {
  2. created() {
  3. this.tableLayout.addObserver(this);
  4. },
  5. destroyed() {
  6. this.tableLayout.removeObserver(this);
  7. },
  8. computed: {
  9. tableLayout() {
  10. let layout = this.layout;
  11. if (!layout && this.table) {
  12. layout = this.table.layout;
  13. }
  14. if (!layout) {
  15. throw new Error('Can not find table layout.');
  16. }
  17. return layout;
  18. }
  19. },
  20. mounted() {
  21. this.onColumnsChange(this.tableLayout);
  22. this.onScrollableChange(this.tableLayout);
  23. },
  24. updated() {
  25. if (this.__updated__) return;
  26. this.onColumnsChange(this.tableLayout);
  27. this.onScrollableChange(this.tableLayout);
  28. this.__updated__ = true;
  29. },
  30. methods: {
  31. onColumnsChange(layout) {
  32. const cols = this.$el.querySelectorAll('colgroup > col');
  33. if (!cols.length) return;
  34. const flattenColumns = layout.getFlattenColumns();
  35. const columnsMap = {};
  36. flattenColumns.forEach((column) => {
  37. columnsMap[column.id] = column;
  38. });
  39. for (let i = 0, j = cols.length; i < j; i++) {
  40. const col = cols[i];
  41. const name = col.getAttribute('name');
  42. const column = columnsMap[name];
  43. if (column) {
  44. col.setAttribute('width', column.realWidth || column.width);
  45. }
  46. }
  47. },
  48. onScrollableChange(layout) {
  49. const cols = this.$el.querySelectorAll('colgroup > col[name=gutter]');
  50. for (let i = 0, j = cols.length; i < j; i++) {
  51. const col = cols[i];
  52. col.setAttribute('width', layout.scrollY ? layout.gutterWidth : '0');
  53. }
  54. const ths = this.$el.querySelectorAll('th.gutter');
  55. for (let i = 0, j = ths.length; i < j; i++) {
  56. const th = ths[i];
  57. th.style.width = layout.scrollY ? layout.gutterWidth + 'px' : '0';
  58. th.style.display = layout.scrollY ? '' : 'none';
  59. }
  60. }
  61. }
  62. };