解决多端开发H5/小程序 使用createIntersectionObserver造成报错Cannot read property ‘bottom‘ of null

场景描述:在使用uniapp框架开发小程序和H5多端兼容开发 其中涉及到中英文切换 在切换的时候会重置页面,小程序上不会有报错,倒是h5上会提示Cannot read property ‘bottom’ of null

报错原因:

 小程序中使用uni.reLaunch重置页面,会重置createIntersectionObserver,但是h5不会

解决方法

在离开页面时this.obAnchor.disconnect() 
// 创建监听时 this.obAnchor = uni.createIntersectionObserver(this)

优化建议

由于使用的场景是头部通用组件 每个页面都需要清除,如果是使用vue开发的小伙伴建议使用混入(react的小伙伴可以使用装饰器来扩展类)

下面是使用vue的方法

全局混入
 Vue.mixin({
    data: function () {
      return {
      }
    },
    computed: {
    },
    onLoad () {}beforeDestroy () {
    // #ifdef H5
    if (this.$refs.header) {
      this.$refs.header.clearObserver()
    }
    // #endif
  }
  })
组件使用示例
<Header ref="header"/>
header组件部分代码
mounted () {
    const sys = uni.getSystemInfoSync()
    this.navHeight = sys.statusBarHeight + 46
    try {
      this.obAnchor = uni.createIntersectionObserver(this)
      this.obAnchor.relativeToViewport({ top: 20 })
        .observe('#nav-anchor', (res) => {
          const { intersectionRatio } = res
          this.isShowStatic = intersectionRatio !== 1
        })
    } catch (error) {
      console.log('监听失败')
    }
  },
  methods: {
    clearObserver () {
      if (this.obAnchor) {
        this.obAnchor.disconnect()
      }
    }
  }
ps:局部混入肯定比全局混入性能更好 追求性能就局部混入
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值