子组件封装
<template>
<div :id="myChart" :style="{ width: width, height: height }"></div>
</template>
<script>
// import { baseurl } from "@/api/common/request";
import * as echarts from "echarts";
export default {
props: {
widthHeight: {type: Object},
},
data() {
return {
myChart:"myChart"+new Date().valueOf()
data: [
{ name: "Mon", value: 200, color: "#a90000" },
{ name: "Tue", value: 250, color: "#ccc" },
{ name: "Wed", value: 100, color: "#eee" },
{ name: "Thu", value: 180, color: "#000" },
{ name: "Fri", value: 220, color: "#5C7BD9" },
{ name: "Sat", value: 280, color: "#B5D5FF" },
{ name: "Sun", value: 130, color: "#a90000" },
],
name: [],
valueColor: [],
width: "300px",
height: "300px",
title: null,
};
},
mounted() {
this.change();
this.width=this.widthHeight.ewidth
this.height=this.widthHeight.eheight
},
methods: {
// 拆分请求过来的数据
change() {
//for循环外应该有一层axios请求,成功时在then里面写for循环
for (var i = 0; i < this.data.length; i++) {
this.name.push(this.data[i].name);
this.valueColor.push({
value: this.data[i].value,
itemStyle: {color:this.data[i].color},
});
if (this.valueColor.length == this.data.length) {
// 当数据分离完再调用drawLine方法
this.drawLine();
}
}
},
// 初始化图表
drawLine() {
let newPromise = new Promise((resolve) => {
resolve();
});
//然后异步执行echarts的初始化函数
newPromise.then(() => {
// 此dom为echarts图标展示dom
let myChart = echarts.init(document.getElementById(this.myChart));
myChart.setOption({
xAxis: {
type: "category",
data: this.name,
},
yAxis: {
type: "value",
},
series: [
{
data: this.valueColor,
type: "line",
smooth: true,//是否圆滑
},
],
});
});
},
},
};
</script>
父组件调用
//使用
<lineTwo :widthHeight="widthHeight"></lineTwo>
//引入
import lineTwo from "@/components/common/eaharts/line/lineTwo";
//注册
components: { lineTwo },
//传参给子组件
widthHeight: {
ewidth: "500px",
eheight: "250px",
},