需求:显示默认时间为当前时间至7天之前时间 去请求数据
实现效果:
1.安装Echarts
cnpm install echarts -S
2.在vue项目中使用Echarts
父组件使用子组件的代码
template区的使用
<BarChart
:labelList="chartData.labelList"
:checkOutValueList="chartData.checkOutValueList"
:putInValueList="chartData.putInValueList"
/>
数据 (引入组件,注册组件,定义图表需要的数据)
data() {
return {
chartData: {}, //echart图表数据
};
},
接口返回数据
created() {
this.getList();
},
methods: {
getList() {
let data = {
updateDate: this.deviceFormData.time,
pn: this.pn,
};
getInOutData(data).then((res) => {
this.chartData = res;
console.log(this.chartData, "子组件this.chartData");
});
},
}
数据结构:
子组件页面代码(接收数据,并渲染)
<template>
<div
:class="className"
:style="{ height: height, width: width }"
id="myChart"
/>
</template>
<script>
import echarts from "echarts";
export default {
props: {
//接受父组件传递来的数据
labelList: Array,
checkOutValueList: Array,
putInValueList: Array,
className: {
type: String,
default: "chart",
},
width: {
type: String,
default: "100%",
},
height: {
type: String,
default: "300px",
},
},
data() {
return {};
},
watch: {
labelList: function (newQuestion, oldQuestion) {
this.initChart();
},
},
mounted() {
this.initChart();
},
methods: {
initChart() {
// 创建 echarts 实例。
var myChartOne = echarts.init(document.getElementById("myChart"));
myChartOne.setOption({
tooltip: {
trigger: "axis",
axisPointer: {
type: "shadow",
},
},
legend: {
textStyle: {
color: "#ffffff",
},
},
grid: {
left: "3%",
right: "4%",
bottom: "3%",
containLabel: true,
},
xAxis: [
{
type: "category",
data: this.labelList,
axisTick: {
alignWithLabel: true,
},
axisLabel: {
textStyle: {
color: "#fff", //坐标值得具体的颜色
},
},
},
],
yAxis: [
{
type: "value",
axisLabel: {
textStyle: {
color: "#fff", //坐标值得具体的颜色
},
},
},
],
series: [
{
name: window.vm.$i18n.t("barChart.putQuantity"),
type: "bar",
data: this.checkOutValueList,
itemStyle: {
color: "#9B59B6",
},
},
{
name: window.vm.$i18n.t("barChart.outQuantity"),
type: "bar",
data: this.putInValueList,
itemStyle: {
color: "#DFBA49",
},
},
],
});
},
},
};
</script>