父组件
获取数据,随后传递给子组件. 一定要加判断,因为xhr获取数据是异步的,不加判断会把初始化的空对象传给组件,所以要加判断,等从接口获取到数据后再展传递数据。
使用Object.keys().length方法判断对象是否为空
<LineChart :reportsList="reportsList" v-if="Object.keys(reportsList).length" />
data() {
return {
reportsList: {},
};
},
created() {
reportsGet("reports/type/1").then((res) => {
console.log(res);
let { meta, data } = res.data;
if (meta.status == 200) {
this.reportsList = data;
} else {
this.$message.error(meta.msg);
}
});
},
折线图子组件
父组件传过来的数据用来赋值给lineList数据,方便修改,不会影响原数据
data() {
return {
lineList: {},
};
},
props: {
reportsList: {
type: Object,
default: () => {
return {
title: {
text: "折线图",
},
tooltip: {},
xAxis: {
axisLabel: { interval: 0, rotate: 0, margin: 15 },
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
},
yAxis: {},
series: [
{
name: "销量",
type: "line",
data: [5, 20, 36, 10, 10, 20],
},
],
};
},
},
},
mounted() {
var myChart = echarts.init(this.$refs.main);
把父组件的数据传递给子组件后再赋值给data中的lineList
这里要使用深浅拷贝
this.lineList = JSON.parse(JSON.stringify(this.reportsList));
对象key的父级为空就必须要先给k的父级设置个空对象再赋值
this.lineList.title = {
text: "折线图",
};
/* 给折线图设置上下左右的距离 */
原本的数据中legend(top的父级)是有数据的,所以直接添加即可
this.lineList.legend.top='10%';
之所以写成以下形式,因为这种形式是添加,如果直接this.lineList.xAxis.axisLabel =xxx 就是直接覆盖了,原xAxis.axisLabel里的内容就消失了
this.lineList.xAxis[0].axisLabel =
{ interval: 0, rotate: 30, margin: 15 };
this.lineList.grid = {
top: "30%",
width: "80%",
height: "50%",
left: "20%",
};
/* 把折线图所属区域删掉 */
this.lineList.series.forEach(r=>{
delete r.areaStyle;
r.smooth=true
})
myChart.setOption(this.lineList);
window.LineChart = myChart;
},
};