当前位置: 首页 > 工具软件 > BetterScroll > 使用案例 >

Vue3动态渲染,betterScroll无法滚动(图片加载也兼容)

谯皓君
2023-12-01
// 解决动态渲染无法滚动问题
let observer
onMounted(() => {
  nextTick(() => {
    const observerOptions = {
      subtree: true, // 观察后代节点
      childList: true, // 观察目标子节点添加或者删除
    }
    const callback = (mutationList, observer) => {
      for (let i = 0; i < mutationList.length; i++) {
        const mutation = mutationList[i]
        if (mutation.type !== 'childList') continue

        // 节点渲染完刷新滚动
        nextTick(refreshAppPageScroll)

        // 新增图片加载完后刷新滚动
        let imgs = mutation.target.getElementsByTagName('img')
        if (!imgs.length) continue
        const promiseList = [...imgs].map(
          (img) =>
            new Promise((resolve) => {
              img.addEventListener('load', resolve)
            })
        )
        Promise.all(promiseList).then(refreshAppPageScroll)
      }
    }
    observer = new MutationObserver(callback)
    observer.observe(pagebody.value, observerOptions)
  })
})
onUnmounted(observer?.disconnect) // 停止观察
 类似资料: