uniapp微信小程序echarts使用cdn引入
时间: 2024-06-02 07:05:19 浏览: 370
uniapp是一款跨平台的开发框架,可以帮助开发者快速地构建出多端应用。而echarts是一个非常优秀的可视化图表库,在uniapp中也可以很方便地引入使用。
如果你要在uniapp中使用微信小程序版的echarts,并且使用cdn引入,可以按照以下步骤:
1. 在项目根目录下的`pages.json`文件中添加如下配置:
```json
"usingComponents": {
"ec-canvas": "路径/ec-canvas/ec-canvas"
}
```
2. 在`ec-canvas`文件夹下新建一个`ec-canvas.vue`文件,并在其中添加如下代码:
```html
<template>
<canvas :canvas-id="canvasId" class="ec-canvas"></canvas>
</template>
<script>
import * as echarts from '路径/echarts.min.js'
export default {
props: {
canvasId: {
type: String,
default: 'ec-canvas'
},
ec: {
type: Object,
default: () => {}
}
},
data() {
return {
chart: null,
initOpts: {}
}
},
mounted() {
this.init()
},
methods: {
init() {
if (!this.ec) return
this.initOpts = Object.assign({}, this.ec, {
renderer: 'canvas',
width: this.getWidth(),
height: this.getHeight()
})
this.chart = echarts.init(this.$refs.canvas, null, this.initOpts)
this.chart.setOption(this.initOpts.option)
},
getWidth() {
const { width } = uni.getSystemInfoSync()
return width
},
getHeight() {
const { statusBarHeight, windowHeight } = uni.getSystemInfoSync()
const query = uni.createSelectorQuery().in(this)
query.select('.ec-canvas').boundingClientRect(data => {
this.height = data.height
}).exec()
return windowHeight - statusBarHeight - this.height
}
},
watch: {
ec: {
handler(val) {
if (!this.chart) return
this.initOpts = Object.assign({}, val, {
renderer: 'canvas',
width: this.getWidth(),
height: this.getHeight()
})
this.chart.setOption(this.initOpts.option)
},
deep: true
}
},
beforeDestroy() {
if (this.chart) {
this.chart.dispose()
this.chart = null
}
}
}
</script>
<style scoped>
.ec-canvas {
width: 100%;
height: 100%;
}
</style>
```
3. 在需要使用echarts的页面中,引入echarts的cdn链接,例如:
```html
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/4.9.0/echarts.min.js"></script>
```
4. 在页面中使用`ec-canvas`组件,并传入相应的参数,例如:
```html
<template>
<view>
<ec-canvas :ec="ec" :canvas-id="canvasId"></ec-canvas>
</view>
</template>
<script>
export default {
data() {
return {
canvasId: 'my-echart',
ec: {
option: {
title: {
text: '某站点用户访问来源',
subtext: '纯属虚构',
left: 'center'
},
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 10,
data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
},
series: [
{
name: '访问来源',
type: 'pie',
radius: ['50%', '70%'],
avoidLabelOverlap: false,
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '30',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: [
{ value: 335, name: '直接访问' },
{ value: 310, name: '邮件营销' },
{ value: 234, name: '联盟广告' },
{ value: 135, name: '视频广告' },
{ value: 1548, name: '搜索引擎' }
]
}
]
}
}
}
}
}
</script>
```
这样就可以在uniapp中使用微信小程序版的echarts并使用cdn引入了。
阅读全文