uni-app使用Renderjs
uniapp生成本地打包App资源后为什么无法操作Dom
?
首先统一打包方式,使用Hbuild生成本地app打包资源后,通过Android Studio打包成app。Uniapp生成本地app资源是基于Webview方式运行在Android壳子上的。
Webview是一种在移动应用中嵌入Web内容的组件,它提供了将Web内容显示在移动应用中的能力。尽管Webview可以展示Web页面,但它并没有直接提供完整的DOM(文档对象模型)。
Webview的实现方式因平台而异,但通常基于操作系统提供的原生控件,并使用浏览器引擎来渲染Web内容。然而,与在浏览器中直接访问Web页面不同,Webview在移动应用中以嵌入的方式存在,并且提供了一些限制和安全性考虑。
renderjs可以帮我解决什么问题?
使用echarts举例:
<template>
<view class="content">
<!-- #ifdef APP-PLUS || H5 -->
<view @click="echarts.onClick" :prop="option" :change:prop="echarts.updateEcharts" id="echarts" class="echarts"></view>
<button @click="changeOption">更新数据</button>
<!-- #endif -->
<!-- #ifndef APP-PLUS || H5 -->
<view>非 APP、H5 环境不支持</view>
<!-- #endif -->
</view>
</template>
// 为了好记, 这里起个名字叫serve层
<script module="serve">
export default {
data() {
return {
option: {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
}
}
},
onLoad() {
},
methods: {
changeOption() {
const data = this.option.series[0].data
// 随机更新示例数据
data.forEach((item, index) => {
data.splice(index, 1, Math.random() * 40)
})
},
onViewClick(options) {
console.log(options)
}
}
}
</script>
<script module="echarts" lang="renderjs">
// 为了好记, 这里起个名字叫resder层
let myChart
export default {
mounted() {
if (typeof window.echarts === 'function') {
this.initEcharts()
} else {
// 动态引入较大类库避免影响页面展示
const script = document.createElement('script')
// view 层的页面运行在 www 根目录,其相对路径相对于 www 计算
script.src = 'static/echarts.js'
script.onload = this.initEcharts.bind(this)
document.head.appendChild(script)
}
},
methods: {
initEcharts() {
myChart = echarts.init(document.getElementById('echarts'))
// 观测更新的数据在 view 层可以直接访问到
myChart.setOption(this.option)
},
updateEcharts(newValue, oldValue, ownerInstance, instance) {
// 监听 service 层数据变更
myChart.setOption(newValue)
},
onClick(event, ownerInstance) {
// 调用 service 层的方法
ownerInstance.callMethod('onViewClick', {
test: 'test'
})
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.echarts {
margin-top: 100px;
width: 100%;
height: 300px;
}
</style>
uniapp中App开发rendderjs的使用交互
serve
层监听prop="option"
变化时执行change:prop="echarts.updateEcharts"
changeOption() {
const data = this.option.series[0].data
// 随机更新示例数据
data.forEach((item, index) => {
data.splice(index, 1, Math.random() * 40)
})
}
获取serve传递过来的ownerInstance
对象
updateEcharts(newValue, oldValue, ownerInstance, instance) {
// 监听 service 层数据变更
myChart.setOption(newValue)
}
使用ownerInstance
反向访问serve
层
// render
onClick(event, ownerInstance) {
// 调用 service 层的方法
ownerInstance.callMethod('onViewClick', {
test: 'test'
})
}
// serve
onViewClick(options) {
console.log(options)
}
需要renderjs的时候在用renderjs
有些场景要同时打包小程序、h5、app,这时候如果要用到echarts图表,使用renderjs
会不兼容小程序
本作品采用《CC 协议》,转载必须注明作者和本文链接