uni-app 在vue3中使用uni.createIntersectionObserver找不到dom节点的问题(实际有相关dom节点)

a7qyws3x  于 7个月前  发布在  uni-app
关注(0)|答案(6)|浏览(180)

问题描述
使用uni.createIntersectionObserver提示找不到dom,实际有dom

复现步骤

  1. <template>
  2. <view class="target"></view>
  3. </template>
  4. <script lang="ts">
  5. import { defineComponent, getCurrentInstance, onMounted } from 'vue'
  6. export default defineComponent({
  7. setup() {
  8. const observer = uni.createIntersectionObserver(getCurrentInstance()?.proxy)
  9. onMounted(function () {
  10. console.log(document.querySelector('.target'))
  11. observer.relativeToViewport({ right: 0, bottom: 0 }).observe('.target', ({ intersectionRatio }) => {
  12. observer.disconnect()
  13. console.log('intersectionRatio', intersectionRatio)
  14. })
  15. })
  16. },
  17. })
  18. </script>
  19. <style lang="scss">
  20. .target {
  21. margin: 25vh auto;
  22. width: 200rpx;
  23. height: 200rpx;
  24. background-color: #f00;
  25. }
  26. </style>

预期结果
uni.createIntersectionObserver正常执行

实际结果
uni.createIntersectionObserver执行不正常,提示找不到对应的dom

系统信息:

  • 发行平台: H5平台
  • 操作系统 chrome
  • HBuilderX版本 vscode
  • uni-app版本
  1. ├─ @dcloudio/uni-app-plus@3.0.0-alpha-3031220220222002
  2. ├─ @dcloudio/uni-app-vite@3.0.0-alpha-3031220220222002
  3. └─ @dcloudio/uni-app-vue@3.0.0-alpha-3031220220222002
  4. ├─ @dcloudio/uni-app-vite@3.0.0-alpha-3031220220222002
  5. ├─ @dcloudio/uni-app-vue@3.0.0-alpha-3031220220222002
  6. ├─ @dcloudio/uni-app@3.0.0-alpha-3031220220222002
  • 设备信息 chrome debugger

补充信息
源代码: uni-app-vue3-bug

evrscar2

evrscar21#

  1. onMounted(() => {
  2. nextTick(() => getDom());
  3. });
  4. const getDom = async () => {
  5. const instance = getCurrentInstance(); // 获取实例
  6. let query = uni.createSelectorQuery().in(instance);
  7. query
  8. .select(". target")
  9. .boundingClientRect((res: any) => {
  10. console.log("boundingClientRect:", res)
  11. })
  12. .exec();
  13. };
ar7v8xwq

ar7v8xwq3#

selector 不能设置成当前组件的最外层元素,因为 6008行 那的 $el 就是最外层元素,再用最外层元素 querySelector ,是找不到本身的

希望官方能优化这个问题

7eumitmz

7eumitmz4#

halo,请问您解决了吗,我也是这个api 一直报 $el.queryselector is not a function

wlsrxk51

wlsrxk515#

在自定义组件中在包一层就可以了

  1. <view class="target">
  2. </view>
  3. <!-- 变成这样 -->
  4. <view class="wrapper">
  5. <view class="target">
  6. </view>
  7. </view>
6tqwzwtp

6tqwzwtp6#

这样写可以

  1. import { onMounted, getCurrentInstance } from "vue";
  2. import type { ComponentInternalInstance } from "vue";
  3. const _this = getCurrentInstance() as ComponentInternalInstance;
  4. const initCreateIntersectionObserver = () => {
  5. uni
  6. .createIntersectionObserver(_this)
  7. .relativeToViewport({ bottom: 0 })
  8. .observe(".target", (res) => {
  9. if (res.intersectionRatio) {
  10. // .....
  11. }
  12. });
  13. };
  14. onMounted(() => {
  15. initCreateIntersectionObserver();
  16. });
展开查看全部

相关问题