在vue 项目中使用 eCharts ,但是项目一直报 init of undefined
,查阅很多资料,方法不一
1,元素没有设长宽
<template>
<div class="container">
<div id="myChart" ref="myChart" style="width: 600px; height: 400px"></div>
</div>
</template>
2,初始化实例应该写在 mounted
mounted() {
let myCharts = this.$echarts.init(this.$refs.myChart); ;
let options = {
title: {
text: "未来一周气温变化", //图表顶部的标题
subtext: "纯属虚构", //副标题
},
tooltip: {
//鼠标悬浮框的提示文字
trigger: "axis",
},
legend: {
data: ["最高气温", "最低气温"],
},
xAxis: [
{
//x轴坐标数据
type: "category",
boundaryGap: false,
data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
},
],
yAxis: [
{
//y轴坐标数据
type: "value",
axisLabel: {
formatter: "{value} °C",
},
},
],
series: [
//驱动图表生成的数据内容数组,几条折现,数组中就会有几个对应对象,来表示对应的折线
{
name: "最高气温",
type: "line", //pie->饼状图 line->折线图 bar->柱状图
data: [11, 11, 15, 13, 12, 13, 10],
},
{
name: "最低气温",
type: "line", //pie->饼状图 line->折线图 bar->柱状图
data: [1, -2, 2, 5, 3, 2, 0],
},
],
};
myCharts.setOption(options);
}
3,mounted
最好加上 $nextTick
init() {
console.log(this.$echarts);
console.log((document.getElementById('myChart')));
let myCharts = this.$echarts.init(this.$refs.myChart); ;
let options = {
title: {
text: "未来一周气温变化", //图表顶部的标题
subtext: "纯属虚构", //副标题
},
tooltip: {
//鼠标悬浮框的提示文字
trigger: "axis",
},
legend: {
data: ["最高气温", "最低气温"],
},
xAxis: [
{
//x轴坐标数据
type: "category",
boundaryGap: false,
data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
},
],
yAxis: [
{
//y轴坐标数据
type: "value",
axisLabel: {
formatter: "{value} °C",
},
},
],
series: [
//驱动图表生成的数据内容数组,几条折现,数组中就会有几个对应对象,来表示对应的折线
{
name: "最高气温",
type: "line", //pie->饼状图 line->折线图 bar->柱状图
data: [11, 11, 15, 13, 12, 13, 10],
},
{
name: "最低气温",
type: "line", //pie->饼状图 line->折线图 bar->柱状图
data: [1, -2, 2, 5, 3, 2, 0],
},
],
};
myCharts.setOption(options);
}
mounted() {
this.$nextTick(() => {
this.init();
});
}
4,以上方法都不行的话检查一下 eCharts 的版本
"echarts": "^5.0", // 替换为4.8.0 || 查看官方推荐的引入方式,版本迭代引入方式有时间会有所不同