vue3中使用echart多个图表,并且可以随着屏幕大小自适应布局
vue3中使用echart多个图表,并且可以随着屏幕大小自适应布局
·
一. 在项目中安装echarts
npm install echarts --save
二. 引入echarts
1. 因为多个地方需要使用到这个echart图表,所以将这个echarts写在自定义组件中,子组件(chart.vue)
<div class="charts">
<div ref="chart" class="sample_chart"></div>
</div>
//chart.vue
//引入echarts
import * as echarts from "echarts";
import { onMounted, ref } from "vue";
const chart = ref(null);
//这里为echarts图表,这里可以根据自己需要来设置
function renderChart() {
const option = {
title: {
text: "统计",
left: "center",
},
tooltip: {
trigger: "item",
},
legend: {
orient: "vertical",
x: "right",
y: "bottom",
},
series: [
{
name: "Access From",
type: "pie",
radius: "70%",
data: [
{ value: 1048, name: "Search Engine" },
{ value: 735, name: "Direct" },
{ value: 580, name: "Email" },
{ value: 484, name: "Union Ads" },
{ value: 300, name: "Video Ads" },
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)",
},
},
label: {
show: true,
position: "inside",
formatter: "{c}", // 显示数值
},
},
],
};
const myChart = echarts.init(chart.value);
myChart.setOption(option);
}
//echarts图表自适应方法
const resizeChart = () => {
const myChart = echarts.init(chart.value);
window.addEventListener(
"resize",
() => {
myChart.resize();
},
false
);
};
//将图表自适应方法暴露给父组件
defineExpose({ resizeChart });
onMounted(() => {
renderChart();
resizeChart();
});
echarts图表一定要有width和height,因为这里需要一行同时显示两个图表,父级有设置display:flex;所以这里子元素需要设置flex:1。
.charts {
margin-left: 30px;
flex: 1;
height: 400px;
.sampleNum_chart {
width: 100%;
height: 100%;
background-color: #fff;
}
}
2. 父组件(index.vue)
<div class="project-chart">
<chart ref="chart1Ref"></chart>
<chart ref="chart2Ref"></chart>
</div>
const chart1Ref= ref(null);
const chart2Ref= ref(null);
onMounted(() =>{
//在父组件中调用子组件的自适应方法
chart1Ref.value.resizeChart();
chart2Ref.value.resizeChart()
})
.project-chart {
display: flex;
}
三. 样式展示
更多推荐
已为社区贡献8条内容
所有评论(0)