前言
本文使用的echarts版本为5.3.1,详细文档可见:
Echarts 官方文档
文中案例基于vue3编写,有关js部分使用的是"script setup"语法糖形式
一、安装并导入echart
1.npm下载包
npm i echarts --save
2.配置echarts
这里介绍使用 provide 和 injec 配置 echartst
provide、injec 可以实现嵌套组件之间进行传递数据和方法
在父组件使用provide可向子代组件传递数据;子级组件使用inject来获取上级组件传递过来的数据
在 app.vue 下
<script>
import { provide } from 'vue'
import * as echarts from 'echarts'
export default {
setup() {
provide('echarts',echarts)
},};
</script>
在子代组件,使用 inject 获取 echarts 后便可使用
<script setup>
import { inject } from "vue"
const echarts = inject("echarts")
</script>
二、使用echarts
这里举一个小例子:
<template>
<div class="echart" ref="chartDom"></div>
</template>
<script setup>
//按需导入需要用到的 vue函数 和echarts
import { ref,inject,onMounted } from "vue";
const echarts = inject("echarts");
//获取 dom 和 父组件数据 并定义"myChart"用于初始化图表
const chartDom = ref()
let myChart = null;
let option = reactive ({
title: { text: "总用户量" },tooltip: {},xAxis: {
data: ["12-3","12-4","12-5","12-6","12-7","12-8"],},yAxis: {},series: [
{
name: "用户量",type: "line",data: [5,20,36,10,20],],})
//页面成功渲染,开始绘制图表
onMounted(() => {
myChart = echarts.init(chartDom.value)
myChart.setoption(props.option,true);
})
</script>
<style lang="scss" scoped>
.echart {
width: 800px;
height: 500px;
}
</style>
效果:
三、封装echarts为组件
echarts封装组件:
<template>
<div class="echart" ref="chartDom"></div>
</template>
<script setup>
//按需导入需要用到的 vue函数 和 echarts
import { ref,onMounted,onBeforeUnmount,defineProps,watch } from "vue";
const echarts = inject("echarts");
//获取 dom 和 父组件数据 并定义"myChart"用于初始化图表
const chartDom = ref()
let myChart = null;
const props = defineProps({
option: Object,})
//重绘图表函数
const resizeHandler = () => {
myChart.resize();
}
//设置防抖,保证无论拖动窗口大小,只执行一次获取浏览器宽高的方法
const debounce = (fun,delay) => {
let timer;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fun();
},delay);
}
};
const cancalDebounce = debounce(resizeHandler,500);
//页面成功渲染,开始绘制图表
onMounted(() => {
//配置为 svg 形式,预防页面缩放而出现模糊问题;图表过于复杂时建议使用 Canvas
myChart = echarts.init(chartDom.value,null,{renderer:'svg'})
// myChart = echarts.init(chartDom.value)
myChart.setoption(props.option,true);
//自适应不同屏幕时改变图表尺寸
window.addEventListener('resize',cancalDebounce);
})
//页面销毁前,销毁事件和实例
onBeforeUnmount(() => {
window.removeEventListener('resize',cancalDebounce)
myChart.dispose()
})
//监听图表数据时候变化,重新渲染图表
watch(() => props.option,() => {
myChart.setoption(props.option,true);
},{ deep: true })
</script>
<style lang="scss" scoped>
.echart {
width: 100%;
height: 100%
}
</style>
上面的在不同屏幕大小下自适应重绘图表需在 flexible.js 的配置下才有效,有关 flexible 的配置可参考 “移动端与大屏幕自适应适配方案”
注:在调用该组件时需传入 option配置值 和 设置组件大小