1.不加watch监听前显示如下图,且数据不能渲染到页面中

添加watch监听后页面效果渲染出来

// watch监听后就可以显示
watch: {
datas: {
deep: true,
handler(newValue) {
// console.log(newValue)
this.drawLine();
},
},
},
完整代码如下
<template>
<div class="box">
<div id="myChart" :style="{ width: '800px', height: '400px' }"></div>
</div>
</template>
<script>
export default {
data() {
return {
msg: "fafa",
num: [],
datas: [],
};
},
// watch监听后就可以显示
watch: {
datas: {
deep: true,
handler(newValue) {
// console.log(newValue)
this.drawLine();
},
},
},
mounted() {
this.drawLine();
// console.log(this.$echarts);
},
// 接口部分
created() {
// ----------
// 调接口
fetch("http://api.cat-shop.penkuoer.com/api/v1/products")
.then((res) => res.json())
.then((res) => {
console.log(res.products);
this.num = res.products;
console.log(this.num[0]);
for (let i = 0; i < this.num.length; i++) {
this.datas.push(this.num[i].price);
console.log(this.datas);
}
});
// ---------
},
methods: {
drawLine() {
// 基于准备好的dom,初始化echarts实例
let myChart = this.$echarts.init(document.getElementById("myChart"));
// 绘制图表
myChart.setOption({
title: {
text: "Distribution of Electricity",
subtext: "Fake Data",
},
tooltip: {
trigger: "axis",
axisPointer: {
type: "cross",
},
},
toolbox: {
show: true,
feature: {
saveAsImage: {},
},
},
xAxis: {
type: "category",
boundaryGap: false,
// prettier-ignore
data: ['00:00', '01:15', '02:30', '03:45', '05:00', '06:15', '07:30', '08:45', '10:00', '11:15', '12:30', '13:45', '15:00', '16:15', '17:30', '18:45', '20:00', '21:15', '22:30', '23:45'],
},
yAxis: {
type: "value",
axisLabel: {
formatter: "{value} W",
},
axisPointer: {
snap: true,
},
},
visualMap: {
show: false,
dimension: 0,
pieces: [
{
lte: 6,
color: "green",
},
{
gt: 6,
lte: 8,
color: "red",
},
{
gt: 8,
lte: 14,
color: "green",
},
{
gt: 14,
lte: 17,
color: "red",
},
{
gt: 17,
color: "green",
},
],
},
series: [
{
name: "Electricity",
type: "line",
smooth: true,
// prettier-ignore
data: this.datas,
markArea: {
itemStyle: {
color: "rgba(255, 173, 177, 0.4)",
},
data: [
[
{
name: "Morning Peak",
xAxis: "07:30",
},
{
xAxis: "10:00",
},
],
[
{
name: "Evening Peak",
xAxis: "17:30",
},
{
xAxis: "21:15",
},
],
],
},
},
],
});
},
},
};
</script>
<style scoped>
.box {
margin-top: 50px;
}
</style>
补充:或者直接在发完请求之后再渲染,可以把监听去掉,也能实现效果
