完整代码:
<template>
<div class="bigbox">
<div id="myCharta"></div>
</div>
</template>
<script>
export default {
name: "Echarts",
data() {
return {
Bvalues: [],
};
},
// mounted() {
// this.init();
// },
created() {
fetch("http://api.cat-shop.penkuoer.com/api/v1/products")
.then((res) => res.json())
.then((res) => {
console.log(res.products);
for (let i = 0; i < res.products.length; i++) {
// 将取到的price和name数据组成新的数组
var litter = {
value: res.products[i].price,
name: res.products[i].name,
};
// 将新数组添加到Bvalues中
this.Bvalues.push(litter);
}
console.log(this.Bvalues);
this.drawLine();
});
},
methods: {
init() {
this.drawLine();
},
drawLine() {
// 基于准备好的dom,初始化echarts实例
let myChart = this.$echarts.init(document.getElementById("myCharta"));
// 绘制图表
myChart.setOption(
{
title: {
text: "Referer of a Website",
subtext: "Fake Data",
left: "center",
},
tooltip: {
trigger: "item",
},
legend: {
orient: "vertical",
left: "left",
},
series: [
{
name: "Access From",
type: "pie",
radius: "50%",
data: this.Bvalues,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)",
},
},
},
],
},
true
);
},
},
};
</script>
<style scoped>
.bigbox {
width: 100%;
height: 100%;
/* background-color: cadetblue; */
display: flex;
}
#myCharta {
width: 800px;
height: 400px;
}
</style>
主要部分:
created() {
fetch("http://api.cat-shop.penkuoer.com/api/v1/products")
.then((res) => res.json())
.then((res) => {
console.log(res.products);
for (let i = 0; i < res.products.length; i++) {
// 将取到的price和name数据组成新的数组
var litter = {
value: res.products[i].price,
name: res.products[i].name,
};
// 将新数组添加到Bvalues中
this.Bvalues.push(litter);
}
console.log(this.Bvalues);
this.drawLine();
});
},