index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { VantComponent } from '../common/component';
  2. VantComponent({
  3. props: {
  4. zIndex: {
  5. type: Number,
  6. value: 99
  7. },
  8. offsetTop: {
  9. type: Number,
  10. value: 0
  11. },
  12. disabled: Boolean
  13. },
  14. data: {
  15. wrapStyle: '',
  16. containerStyle: ''
  17. },
  18. methods: {
  19. setStyle() {
  20. const { offsetTop, height, fixed, zIndex } = this.data;
  21. if (fixed) {
  22. this.setData({
  23. wrapStyle: `top: ${offsetTop}px;`,
  24. containerStyle: `height: ${height}px; z-index: ${zIndex};`
  25. });
  26. }
  27. else {
  28. this.setData({
  29. wrapStyle: '',
  30. containerStyle: ''
  31. });
  32. }
  33. },
  34. observerContentScroll() {
  35. const { offsetTop } = this.data;
  36. const intersectionObserver = this.createIntersectionObserver({
  37. thresholds: [0, 1]
  38. });
  39. this.intersectionObserver = intersectionObserver;
  40. intersectionObserver.relativeToViewport({ top: -offsetTop });
  41. intersectionObserver.observe('.van-sticky', (res) => {
  42. if (this.data.disabled) {
  43. return;
  44. }
  45. // @ts-ignore
  46. const { top, height } = res.boundingClientRect;
  47. const fixed = top <= offsetTop;
  48. this.$emit('scroll', {
  49. scrollTop: top,
  50. isFixed: fixed
  51. });
  52. this.setData({ fixed, height });
  53. wx.nextTick(() => {
  54. this.setStyle();
  55. });
  56. });
  57. }
  58. },
  59. mounted() {
  60. this.observerContentScroll();
  61. },
  62. destroyed() {
  63. this.intersectionObserver.disconnect();
  64. }
  65. });