1. uniapp 獲取dom元素的寬高
在uniapp 中由于他禁止操作dom,所以不能直接獲取dom元素,框架本身提供了獲取元素寬高的方法
let obj = uni.createSelectorQuery().select('xx') // xx為class或者id,如 .block, #block
obj.boundingClientRect(function (data) { // data - dom中的參數(shù),寬高等
console.log(data)
}).exec()
2. renderjs 獲取dom元素
注:只支持 H5 和 App,官網(wǎng)詳見 https://uniapp.dcloud.io/frame?id=renderjs
1. 注意事項(xiàng)
- 目前僅支持內(nèi)聯(lián)使用。
- 不要直接引用大型類庫,推薦通過動(dòng)態(tài)創(chuàng)建 script 方式引用。
- 可以使用 vue 組件的生命周期不可以使用 App、Page 的生命周期
- 視圖層和邏輯層通訊方式與 WXS 一致,另外可以通過 this.$ownerInstance 獲取當(dāng)前組件的 ComponentDescriptor 實(shí)例。
- 觀測(cè)更新的數(shù)據(jù)在視圖層可以直接訪問到。
- APP 端視圖層的頁面引用資源的路徑相對(duì)于根目錄計(jì)算,例如:./static/test.js。
- APP 端可以使用 dom、bom API,不可直接訪問邏輯層數(shù)據(jù),不可以使用 uni 相關(guān)接口(如:uni.request)
- H5 端邏輯層和視圖層實(shí)際運(yùn)行在同一個(gè)環(huán)境中,相當(dāng)于使用 mixin 方式,可以直接訪問邏輯層數(shù)據(jù)。
2. 基本用法
// test 為renderjs模塊名稱,lang固定寫法
<script module="test" lang="renderjs">
export default {
// 與uni寫法一致
}
</script>
3. 案例分析
- 在renderjs的script中,是無法獲取到uni中script--data中的數(shù)據(jù)的,所以要通過一定的方式去傳輸
- 在renderjs中,調(diào)用方法時(shí)也可以通過this.$ownerInstance.callMethod('函數(shù)名', 數(shù)據(jù))向uni的script發(fā)送
<template>
<view class="demo">
<!-- info隨便寫,但是要與chang后面的一致,text是renderjsmodule名稱 -->
<!--data是要想renderjs發(fā)送的數(shù)據(jù),updateData是renderjs中的監(jiān)聽方法 -->
<view :info="data" :change:info="text.updateData" ref="video"></view>
</view>
</template>
<!-- 普通的script標(biāo)簽 -->
<script>
export default {
data(){
return {
data: "hello"
}
},
methods:{
sendMsg(msg) {
console.log(msg) // 不好
}
}
}
</script>
<!-- renderjs的script標(biāo)簽 -->
<script module="text" lang="renderjs">
export default {
data(){
return {
}
},
methods:{
onClick(event, ownerInstance) {
// 向 uni 的script發(fā)送信息
this.$ownerInstance.callMethod('sendMsg', '不好')
},
updateData(newValue, oldValue, ownerInstance, instance) {
// newValue: 新數(shù)據(jù)
// oldValue: 老數(shù)據(jù)
},
}
}
</script>
注: 由于renderjs與uni的script運(yùn)行在同一環(huán)境,不能保證加載順序,所以,盡量把操作dom部分放在renderjs中,所有數(shù)據(jù)通過數(shù)據(jù)傳遞后,在renderjs中操作
在renderjs中,可能會(huì)有獲取不到數(shù)據(jù)的情況,請(qǐng)確保組件數(shù)據(jù)優(yōu)先與renderjs加載,確定所傳輸?shù)臄?shù)據(jù)有值