vue3动态的切换earchs图表的数据
1、首先进行下载模块
我这里通过yarn add echarts,当然也可以使用npm i echarts
2、然后在main里进行引入全局的
import * as echarts from "echarts";
const app = createApp(App);
app.echarts = echarts;
3、组件内进行使用earchs创建实例
注意:这里在虽然给绑定的数据进行创建变量便于切换,但是实例已经创建,所以需要进行销毁,否则会报下面这个错误
echarts.js:30331 There is a chart instance already initialized on the dom.
4、接下来就是代码
html
<template>
<div>
<p >
<button
@click="getBtnClick(0)"
>
<span>我是图表1</span>
</button>
<button
@click="getBtnClick(1)"
>
<span>我是图表2</span>
</button>
</p>
<div class="status_table_earchs" id="state_earchs"></div>
</div>
</template>
javascript
<script>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
export default {
name: "Echarts",
components: {},
setup() {
const getBtnClick = (ind) => {
if (ind === 0) {
y1_list.value = [96, 97, 99, 98, 94, 96];
y2_list.value = [81, 88, 75, 82, 78, 90];
Refresh();
} else {
y1_list.value = [90, 92, 95, 89, 90, 92];
y2_list.value = [80, 88, 89, 70, 78, 80];
Refresh();
}
};
const x_list = ref([
"一月",
"三月",
"五月",
"七月",
"九月",
十一月",
]);
const y1_list = ref([96, 97, 99, 98, 94, 96]);
const y2_list = ref([81, 88, 75, 82, 78, 90]);
let myChart;
const Refresh = () => {
// 进行判断实例是否存在,存在则初始的时候进行销毁
if (myChart) {
myChart.dispose();
myChart = null;
}
myChart = echarts.init(document.getElementById("state_earchs"));
let option = {
title: {
right: "center",
text: earchsTitle.value,
textStyle: {
color: "#0C0D0E",
rich: {
a: {
fontSize: "12",
height: 20,
width: 20,
},
},
},
padding: [22, 0, 0, 32],
},
legend: {
right: "right",
bottom: "middle",
data: ["使用率1", "使用率2"],
icon: "circle",
},
grid: {
left: 55,
right: 150,
},
xAxis: {
type: "category",
data: x_list.value,
//坐标轴刻度相关设置
axisTick: {
show: false,
},
//坐标轴轴线展示
axisLine: {
show: true,
lineStyle: {
color: "#dddddd",
},
},
axisLabel: {
color: "#333", //颜色
fontSize: 14, //大小
},
//坐标轴两边留白策略
boundaryGap: true,
},
tooltip: {
trigger: "axis",
},
yAxis: {
name: "单位:%",
nameTextStyle: {
color: "#000",
fontSize: 18,
fontWeight: 400,
padding: 5,
},
type: "value",
splitLine: {
lineStyle: {
type: "solid",
},
},
axisLabel: {
color: "#333", //颜色
fontSize: 14, //大小
},
},
series: [
{
name: "使用率1",
symbol: "circle",
symbolSize: 6,
showSymbol: false,
data: y1_list.value,
type: "line",
itemStyle: {
color: "red",
},
},
{
name: "使用率2",
symbol: "circle",
symbolSize: 6,
showSymbol: false,
data: y2_list.value,
type: "line",
},
],
};
option && myChart.setOption(option);
window.addEventListener("resize", function () {
myChart.resize();
});
};
onMounted(() => {
Refresh();
});
return {
x_list,
y1_list,
y2_list,
getBtnClick,
Refresh,
};
},
};
</script>
css
<style lang="less" scoped>
/* 样式自己加就行,但是earchs的盒子必须要给宽高 */
.status_table_earchs {
height: 400px;
border: 1px solid #dedede;
}
</style>