uniapp3 不能使用 uni.createselectorquery().in(this) this 是什么原因

在uniapp3中使用uni.createSelectorQuery().in(this)时,提示this无效是什么原因?this应该指向当前组件实例,但实际报错无法识别。请问正确的写法是什么?是否需要额外配置或版本兼容问题?

2 回复

在UniApp 3中,uni.createSelectorQuery().in(this) 报错通常是因为 this 指向问题。
可能原因:

  1. 在非页面/组件作用域调用
  2. 使用了箭头函数改变了 this 指向
  3. 生命周期钩子调用时机不当

解决方案:
确保在 onReady 等生命周期中使用,且 this 指向当前组件实例。


在UniApp 3中,uni.createSelectorQuery().in(this) 无法使用的主要原因是Vue 3 组合式API的 this 上下文变化。在Vue 3中,thissetup() 函数中默认是 undefined,而UniApp 3基于Vue 3开发,因此传统选项式API中的 this 引用方式不再适用。

原因分析:

  1. Vue 3 组合式API:在 setup() 函数中,没有 this 绑定,直接使用 this 会返回 undefined
  2. 作用域问题uni.createSelectorQuery().in(this) 依赖组件实例上下文,但在组合式API中无法通过 this 获取。

解决方案:

  1. 使用 getCurrentInstance 获取组件实例(推荐在组合式API中使用):

    import { getCurrentInstance } from 'vue';
    
    export default {
      setup() {
        const instance = getCurrentInstance();
        const query = uni.createSelectorQuery().in(instance); // 传入组件实例
        
        // 示例:获取元素信息
        query.select('#myElement').boundingClientRect(data => {
          console.log(data);
        }).exec();
      }
    }
    
  2. 在选项式API中继续使用 this(如果项目基于选项式API):

    export default {
      mounted() {
        // 选项式API中 this 仍可用
        const query = uni.createSelectorQuery().in(this);
        query.select('#myElement').boundingClientRect(data => {
          console.log(data);
        }).exec();
      }
    }
    
  3. 使用 uni.createSelectorQuery() 不带 .in(this)(如果选择器在页面全局作用域):

    // 直接创建查询,适用于页面级元素
    const query = uni.createSelectorQuery();
    query.select('#globalElement').boundingClientRect(data => {
      console.log(data);
    }).exec();
    

注意事项:

  • 在自定义组件中使用时,必须通过 .in(instance) 指定组件作用域,否则选择器可能无法正确获取组件内元素。
  • 确保元素已渲染完成(如在 onReadymounted 生命周期中调用)。

根据你的代码结构选择对应方法即可解决问题。

回到顶部