前言
vue3.0已经出来有一段时间了,很多公司也已经开始使用作为默认框架。作为开发,也要持续学习新的知识,这里简单记录下如何在vue3.0中以组件的形式使用echarts,并模拟接口的变更,动态传参。
父组件
<template>
<div class="container">
<el-card style="width:800px">
<div class="box-wrap">
<LineChart :xAxisData="chartData.xAxisData" :seriesData="chartData.seriesData" />
</div>
</el-card>
<!-- 模拟接口数据更改 -->
<el-button type="danger" @click="changeChartData">点击更改传值</el-button>
</div>
</template>
<script >
import { reactive, toRefs, ref } from "vue";
import LineChart from "./conponents/LineChart.vue";
export default {
name: "charts",
components: {
LineChart,
},
setup() {
const chartData = reactive({
xAxisData: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
seriesData: [150, 230, 224, 218, 135, 147, 260],
});
function changeChartData() {
chartData.seriesData = [218, 135, 147, 260, 150, 230, 224];
}
return {
chartData,
changeChartData,
};
},
};
子组件
<template>
<div :id="chartId" :class="className" :style="{height:height,width:width}"></div>
</template>
<script>
import { reactive, toRefs, toRef, watch, onMounted, computed } from "vue";
import * as echarts from "echarts";
export default {
name: "line-chart",
props: {
chartId: {
type: String,
default: () => {
return "line-chart";
},
},
className: {
type: String,
default: () => {
return "line-chart";
},
},
height: {
type: String,
default: "100%",
},
width: {
type: String,
default: "100%",
},
xAxisData: {
type: Array,
default: () => {
return [];
},
},
seriesData: {
type: Array,
default: () => {
return [];
},
},
},
setup(props) {
const { xAxisData, seriesData } = toRefs(props);
// 配置信息
const setOptions = computed(() => {
let option = {
yAxis: {
type: "value",
},
xAxis: {
type: "category",
data: xAxisData.value,
},
series: [
{
type: "line",
data: seriesData.value,
},
],
};
return option;
});
// 创建图表
function initChart() {
let myChart = echarts.init(document.getElementById(props.chartId));
myChart.setOption(setOptions.value);
window.onresize = function () {
//自适应大小
myChart.resize();
};
}
onMounted(() => {
initChart();
});
// 监听传值,刷新图表
watch([seriesData, xAxisData], () => {
initChart();
});
return { setOptions, initChart };
},
};
</script>