tm-sticky.vue 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <template>
  2. <view
  3. class="tm-sticky fulled"
  4. :class="[model_val]"
  5. :style="{
  6. top: model_val == 'top' || model_val == 'static' ? `${top_val}px` : 'auto',
  7. bottom: model_val == 'bottom' ? `${top_val}px` : 'auto'
  8. }"
  9. >
  10. <slot></slot>
  11. </view>
  12. </template>
  13. <script>
  14. /**
  15. * 粘性布局
  16. * @property {String|Number} top = [] 当悬浮时的的偏移量,当model=bottom时,为底部偏移量,单位px
  17. * @property {String} model = [static|top|bottom] 固定的位置
  18. * @example <tm-sticky ></tm-sticky>
  19. */
  20. export default {
  21. name: 'tm-sticky',
  22. props: {
  23. top: {
  24. type: String | Number,
  25. default: 0
  26. },
  27. model: {
  28. type: String,
  29. default: 'static' //static,top,bottom
  30. }
  31. },
  32. destroyed() {
  33. uni.$off('onPageScroll');
  34. },
  35. computed:{
  36. top_val:function(){
  37. return this.top;
  38. },
  39. model_val:function(){
  40. let p = this.model;
  41. // #ifndef H5
  42. if(this.model=='static' && this.istrueStic==false){
  43. return 'top';
  44. }
  45. // #endif
  46. return p;
  47. },
  48. istrueStic:function(){
  49. if(this.nowScrollTop <= this.eleTop){
  50. return true;
  51. }
  52. return false;
  53. }
  54. },
  55. mounted() {
  56. let t= this;
  57. uni.$on('onPageScroll', e => {
  58. t.nowScrollTop = e.scrollTop;
  59. });
  60. this.$nextTick(async function(){
  61. let p = await this.$Querey('.tm-sticky').catch(e=>{})
  62. this.eleTop = p[0].top;
  63. })
  64. },
  65. data() {
  66. return {
  67. nowScrollTop: 0,
  68. eleTop:0
  69. };
  70. }
  71. };
  72. </script>
  73. <style lang="scss" scoped>
  74. .tm-sticky {
  75. &.static {
  76. position: sticky;
  77. position: -webkit-sticky;
  78. }
  79. &.top {
  80. position: fixed;
  81. top: 0;
  82. z-index: 301;
  83. }
  84. &.bottom {
  85. position: fixed;
  86. bottom: 0;
  87. z-index: 301;
  88. }
  89. z-index: 300;
  90. }
  91. </style>