直接步入正题:
第一步:下载
Vue2
npm i echarts -S
npm i echarts-gl -S
Vue3
npm i echarts -S
第二步:引入到main.js文件中
Vue2
import Echarts from 'echarts'
import EchartsGl from 'echarts-gl'
Vue3
import * as Echarts from 'echarts'
第三步:添加到Vue原型上(可选)
Vue2
Vue.prototype.$echarts = Echarts
Vue.prototype.$echartsGl = EchartsGl
Vue3
const app = createApp(App);
app.config.globalProperties.$echarts = Echarts;
第四步:在组件中使用
Vue2
<div id="PRPD"></div>
data() {
return {
prpd: null,
};
},
mounted() {
this.setPRPD();
},
methods: {
// 绘制PRPD
setPRPD() {
let dom = document.getElementById("PRPD");
this.prpd = this.$echarts.getInstanceByDom(dom);
if (!this.prpd) {
this.prpd = this.$echarts.init(dom);
}
this.prpd.clear();
this.prpd.setOption({});
// 监听窗口变化(可选)
window.addEventListener("resize", function () {
this.prpd.resize();
});
},
},
beforeDestroy() {
this.prpd.dispose();
},
Vue3
methods.ts
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
export function getPrototype() {
const { appContext } = getCurrentInstance() as ComponentInternalInstance
const proxy = appContext.config.globalProperties
return {
proxy
}
}
<script setup lang="ts">
import { getPrototype } from "@/utils/methods";
const { proxy } = getPrototype();
将Vue2换成Vue3语法即可
let radar: any;
function setRadar(i) {
let dom = document.getElementById(`radar_class${i + 1}`);//这里渲染了多个图
radar = proxy.$echarts.getInstanceByDom(dom);
if (!radar) {
radar = proxy.$echarts.init(dom);
}
radar.clear();
radar.setOption({});
// 监听窗口变化(可选)
window.addEventListener("resize", function () {
radar.resize();
});
}
接口...{
setRadar(i);
}
onBeforeUnmount(() => {
if (radar) radar.dispose();
});
</script>
下面这个例子可以实现根据数据渲染多个echarts图表
子组件echart.vue
<template>
<div :id="echartID" style="width: 400px; height: 300px; float: left"></div>
</template>
<script setup lang="ts">
import { ref, onBeforeUnmount, onMounted } from "vue";
import { getPrototype } from "@/utils/methods";
const { proxy } = getPrototype();
const props = defineProps({
eData: {
type: Object,
} as any,
});
let eID: any;
let echartID: any = ref(`echart${props.eData.equipmentCode}`);
function setEchart(
yData = props.eData.yData ? props.eData.yData : [],
xData = props.eData.xData ? props.eData.xData : []
) {
let dom = document.getElementById(echartID.value);
eID = proxy.$echarts.getInstanceByDom(dom);
if (!eID) {
eID = proxy.$echarts.init(dom);
}
eID.clear();
eID.setOption({
xAxis: {
type: "category",
data: xData,
},
yAxis: {
type: "value",
},
series: [
{
data: yData,
type: "bar",
},
],
});
// 监听窗口变化(可选)
window.addEventListener("resize", function () {
eID.resize();
});
}
onMounted(() => {
setEchart();
});
onBeforeUnmount(() => {
if (eID) eID.dispose();
});
</script>
父组件
<template>
<Echarts v-for="(e, i) in echartData" :key="i" :eData="e"></Echarts>
</template>
<script setup lang="ts">
...接口.then((res) => {
echartData.value = res.data.data;
});
</script>