赞
踩
通过 SelectorQuery 可以获取页面上节点的一些信息(节点的属性、样式、位置等)
在页面和自定义组件中,wx.createSelectorQuery 和 this.createSelectorQuery 都可以创建一个 SelectorQuery 对象,本文主要讲述两种方式的差异
首先介绍一下代码细节
index WXML
<button bind:tap="onTap">打开 another</button>
<view id="page-view" data-source="index">index → view</view>
index JS
Page({ showFields(root, selector, tag) { root.createSelectorQuery().select(selector) .fields( { id: true, dataset: true }, res => console.log(tag, JSON.stringify(res)) ) .exec() }, onTap() { this.showFields(wx, '#page-view', 'sync wx') this.showFields(this, '#page-view', 'sync this') setTimeout(() => { this.showFields(wx, '#page-view', 'async wx') this.showFields(this, '#page-view', 'async this') }, 1000) wx.navigateTo({ url: '/pages/api/node/another/another' }) } })
another WXML
<view id="page-view" data-source="another">another → view</view>
点击按钮后在控制台打印的日志
sync wx {"id":"page-view","dataset":{"source":"index"}}
sync this {"id":"page-view","dataset":{"source":"index"}}
async wx {"id":"page-view","dataset":{"source":"another"}}
async this {"id":"page-view","dataset":{"source":"index"}}
可以发现,在 index 中,通过 wx.createSelectorQuery 这种方式,获取到了 another 中的节点
首先介绍一下代码细节
index WXML
<my-component></my-component>
<view id="my-component-view" data-source="index">index → view</view>
my-component WXML
<button bind:tap="onTap">showMyCmptView</button>
<view id="my-component-view" data-source="my-component">my-component → view</view>
my-component JS
Component({ methods: { showFields(root, selector, tag) { root.createSelectorQuery().select(selector) .fields( { id: true, dataset: true }, res => console.log(tag, JSON.stringify(res)) ) .exec() }, onTap() { this.showFields(wx, '#my-component-view', 'wx') this.showFields(this, '#my-component-view', 'this') } } })
点击按钮后在控制台打印的日志
wx {"id":"my-component-view","dataset":{"source":"index"}}
this {"id":"my-component-view","dataset":{"source":"my-component"}}
可以发现,在 my-component 中,通过 wx.createSelectorQuery 这种方式,获取到了 index 中的节点
在页面或自定义组件中使用 this.createSelectorQuery() 时,相当于使用 wx.createSelectorQuery().in(this), 把范围限定在了页面或自定义组件内。下面是 SelectorQuery.in() 的相关文档
SelectorQuery.in(Component component)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。