uni-app 开发 APP 如何引用和加载服务器上的 js 文件?附 echart.js 代码例子
2023年08月21日 209
开发 APP 时,很多 js 库都没法使用,会报错,这篇文章解释为什么报错,以及正确使用这些 js 工具库的方法。
在 app 中加载外部 JS 文件报错
朋友在使用 uni-app 开发安卓 APP,使用的是 Vue 页面来开发,在某个页面里需要加载 echarts.js 来展示图表。这位朋友是直接在 Vue 页面中使用 import
来引入 echarts.js,这肯定会报错的,原因是 echarts.js 是一个 for web 的 javascript 库,是不能导入到工程化开发的项目中的,而且 uni-app 运行到安卓 APP 时,js 运行在 js 引擎中,并不是运行在 webview 里,所以会报错。
让 js 文件运行在 webview 里
其实 uni-app 开发 APP Vue 页面时,是可以编写运行在 webview 里的 js 的,那就是使用官方的 renderjs 的方式,在 Vue 文件里插入以下 script 标签来实现,完整的代码例子如下:
<template>
<view class="content">
<view @click="echarts.onClick" :prop="option" :change:prop="echarts.updateEcharts" id="echarts" class="echarts"></view>
<button @click="changeOption">更新数据</button>
</view>
</template>
<script>
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(data) {
console.log(data)
}
}
}
</script>
<script module="echarts" lang="renderjs">
let myChart
export default {
mounted() {
if (typeof window.echarts === 'function') {
this.initEcharts()
} else {
// 这里可以编写常规的网页运行的 js,创建一个 script 标签来加载
const script = document.createElement('script')
// 加载网络上的 js 文件,也可以加载本地的 js 文件
script.src = 'http://xxxxxx/echarts.js'
script.onload = this.initEcharts.bind(this)
document.head.appendChild(script)
}
},
methods: {
initEcharts() {
myChart = echarts.init(document.getElementById('echarts'))
// 在 template 中绑定的 option 可以在这用 this 访问
myChart.setOption(this.option) // 初始化图表
},
updateEcharts(newValue, oldValue, ownerInstance, instance) {
// 数据变化时会触发这个方法,从而更新图表
myChart.setOption(newValue)
},
onClick(event, ownerInstance) {
// 下面这个方法可以调用 Vue 页面 <script> 里的方法
ownerInstance.callMethod('onViewClick', {
test: 'test'
})
}
}
}
</script>
加载任何浏览器的 js 库
上面的代码中,<script lang="renderjs"></script>
中的代码是在 webview 里执行的,可以写任何在网页里运行的 js,比如获取 dom 结构、通过选择器操作 dom、使用浏览器的 api 等,有了这个,就可以动态加载网页开发中使用的库了。
这种方式不仅是在 uni-app 安卓上有用,iOS 用法也是一样的。