weex中,可以通過在特定的節(jié)點(diǎn)上設(shè)置 id 屬性,以此來唯一標(biāo)識(shí)該節(jié)點(diǎn)。然后可以用 this.$el(id)來找到該節(jié)點(diǎn),以scrollToElement() 為例,如下:
<template>
<container>
<text id="top">Top</text>
<container style="height: 10000; background-color: #999999;">
</container>
<text onclick="back2Top">Back to Top</text>
</container>
</template>
<script>
var dom = require('@weex-module/dom');
module.exports = {
methods: {
back2Top: function () {
var top = this.$el('top')
dom.scrollToElement(top, { offset: 10 })
}
}
}
</script>
id 也可以在 repeat語法中使用,更多詳見 展示邏輯控制,但是要確保循環(huán)的節(jié)點(diǎn)需要用不同的id,如下:
<template>
<container>
<image id="{{imgId}}" src="{{imgUrl}}" onclick="getImageId" repeat="{{images}}"></image>
</container>
</template>
<script>
module.exports = {
data: {
images: [
{imgId: 1, imgUrl: '...'},
{imgId: 2, imgUrl: '...'},
{imgId: 3, imgUrl: '...'},
...
]
},
methods: {
getImageId: function(e) {
// get e.target.id
}
}
}
</script>
另外,我們可以通過this.$vm(id) 方法可以訪問子組件的上下文,用法見 組件封裝。