index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import { VantComponent } from '../common/component';
  2. import { pageScrollMixin } from '../mixins/page-scroll';
  3. const ROOT_ELEMENT = '.van-sticky';
  4. VantComponent({
  5. props: {
  6. zIndex: {
  7. type: Number,
  8. value: 99,
  9. },
  10. offsetTop: {
  11. type: Number,
  12. value: 0,
  13. observer: 'onScroll',
  14. },
  15. disabled: {
  16. type: Boolean,
  17. observer: 'onScroll',
  18. },
  19. container: {
  20. type: null,
  21. observer: 'onScroll',
  22. },
  23. scrollTop: {
  24. type: null,
  25. observer(val) {
  26. this.onScroll({ scrollTop: val });
  27. },
  28. },
  29. },
  30. mixins: [
  31. pageScrollMixin(function (event) {
  32. if (this.data.scrollTop != null) {
  33. return;
  34. }
  35. this.onScroll(event);
  36. }),
  37. ],
  38. data: {
  39. height: 0,
  40. fixed: false,
  41. transform: 0,
  42. },
  43. mounted() {
  44. this.onScroll();
  45. },
  46. methods: {
  47. onScroll({ scrollTop } = {}) {
  48. const { container, offsetTop, disabled } = this.data;
  49. if (disabled) {
  50. this.setDataAfterDiff({
  51. fixed: false,
  52. transform: 0,
  53. });
  54. return;
  55. }
  56. this.scrollTop = scrollTop || this.scrollTop;
  57. if (typeof container === 'function') {
  58. Promise.all([this.getRect(ROOT_ELEMENT), this.getContainerRect()]).then(
  59. ([root, container]) => {
  60. if (offsetTop + root.height > container.height + container.top) {
  61. this.setDataAfterDiff({
  62. fixed: false,
  63. transform: container.height - root.height,
  64. });
  65. } else if (offsetTop >= root.top) {
  66. this.setDataAfterDiff({
  67. fixed: true,
  68. height: root.height,
  69. transform: 0,
  70. });
  71. } else {
  72. this.setDataAfterDiff({ fixed: false, transform: 0 });
  73. }
  74. }
  75. );
  76. return;
  77. }
  78. this.getRect(ROOT_ELEMENT).then((root) => {
  79. if (offsetTop >= root.top) {
  80. this.setDataAfterDiff({ fixed: true, height: root.height });
  81. this.transform = 0;
  82. } else {
  83. this.setDataAfterDiff({ fixed: false });
  84. }
  85. });
  86. },
  87. setDataAfterDiff(data) {
  88. wx.nextTick(() => {
  89. const diff = Object.keys(data).reduce((prev, key) => {
  90. if (data[key] !== this.data[key]) {
  91. prev[key] = data[key];
  92. }
  93. return prev;
  94. }, {});
  95. this.setData(diff);
  96. this.$emit('scroll', {
  97. scrollTop: this.scrollTop,
  98. isFixed: data.fixed || this.data.fixed,
  99. });
  100. });
  101. },
  102. getContainerRect() {
  103. const nodesRef = this.data.container();
  104. return new Promise((resolve) =>
  105. nodesRef.boundingClientRect(resolve).exec()
  106. );
  107. },
  108. },
  109. });