skeleton.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // components/skeleton.js
  2. import SystemInfo from 'getSystemInfo.js'
  3. Component({
  4. /**
  5. * 组件的属性列表
  6. */
  7. properties: {
  8. },
  9. /**
  10. * 组件的初始数据
  11. */
  12. data: {
  13. height: 0, //卡片高度,用来做外部懒加载的占位
  14. showSlot: true, //控制是否显示当前的slot内容
  15. skeletonId: ''
  16. },
  17. created() {
  18. //设置一个走setData的数据池
  19. this.extData = {
  20. listItemContainer: null,
  21. }
  22. },
  23. detached() {
  24. try {
  25. this.extData.listItemContainer.disconnect()
  26. } catch (error) {
  27. }
  28. this.extData = null
  29. },
  30. ready() {
  31. this.setData({
  32. skeletonId: this.randomString(8) //设置唯一标识
  33. })
  34. wx.nextTick(() => {
  35. // 修改了监听是否显示内容的方法,改为前后showNum屏高度渲染
  36. // 监听进入屏幕的范围relativeToViewport({top: xxx, bottom: xxx})
  37. let info = SystemInfo.getInfo()
  38. let { windowHeight = 667 } = info.source.system
  39. let showNum = 3 //超过屏幕的数量,目前这个设置是上下2屏
  40. try {
  41. this.extData.listItemContainer = this.createIntersectionObserver()
  42. this.extData.listItemContainer.relativeToViewport({ top: showNum * windowHeight, bottom: showNum * windowHeight })
  43. .observe(`#list-item-${this.data.skeletonId}`, (res) => {
  44. let { intersectionRatio } = res
  45. if (intersectionRatio === 0) {
  46. console.log('【卸载】', this.data.skeletonId, '超过预定范围,从页面卸载')
  47. this.setData({
  48. showSlot: false
  49. })
  50. } else {
  51. console.log('【进入】', this.data.skeletonId, '达到预定范围,渲染进页面')
  52. this.setData({
  53. showSlot: true,
  54. height: res.boundingClientRect.height
  55. })
  56. }
  57. })
  58. } catch (error) {
  59. console.log(error)
  60. }
  61. })
  62. },
  63. /**
  64. * 组件的方法列表
  65. */
  66. methods: {
  67. /**
  68. * 生成随机的字符串
  69. */
  70. randomString(len) {
  71. len = len || 32;
  72. var $chars = 'abcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  73. var maxPos = $chars.length;
  74. var pwd = '';
  75. for (var i = 0; i < len; i++) {
  76. pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  77. }
  78. return pwd;
  79. }
  80. }
  81. })