本文介绍在Echarts中处理无数据状态的三种实现方式。第一种利用title配置项控制显示;第二种通过showLoading API展示加载提示,需注意有数据时调用hideLoading;第三种使用graphic配置项添加自定义图层,支持文字或图片,灵活度最高。
本文旨在记录在Echarts中实现“暂无数据”提示的几种具体方式。
以下各实现方式所依赖的基础HTML代码结构如下:
<div id="noData" style="width: 100%;height:400px;"></div>方法一:利用title配置项实现
const init = (data) => {
const myChart = echarts.init(document.getElementById('noData'))
const option = {
title: {
show: !data.length, // 无数据时展示 title
textStyle: {
color: 'black',
fontSize: 26
},
text: '暂无数据',
left: 'center',
top: 'center'
},
xAxis: {
show: data.length, // 无数据时不展示 x 轴
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data,
type: 'line'
}
]
}
myChart.setOption(option)
}
// const data = [150, 230, 224, 218, 135, 147, 260]
const data = []
init(data)方法二:通过showLoading API实现
const init = (data) => {
const myChart = echarts.init(document.getElementById('noData'))
const option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data,
type: 'line'
}
]
}
myChart.setOption(option)
if (!data.length) {
myChart.showLoading({
text: '暂无数据',
showSpinner: false,
textColor: 'black',
maskColor: 'rgba(255, 255, 255, 1)',
fontSize: '26px',
fontWeight: 'bold'
})
} else {
myChart.hideLoading()
}
}
// const data = [150, 230, 224, 218, 135, 147, 260]
const data = []
init(data)当数据恢复时,务必调用hideLoading()方法,否则图表将无法正常渲染展示。
补充说明:showLoading API的相关细节
方法三:利用graphic配置项实现
const init = (data) => {
const myChart = echarts.init(document.getElementById('noData'))
const option = {
xAxis: {
show: data.length, // 无数据时不展示 x 轴
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data,
type: 'line'
}
],
graphic: {
type: 'text',
left: 'center',
top: 'middle',
silent: true,
invisible: data.length,
style: {
fill: 'black',
fontWeight: 'bold',
text: '暂无数据',
fontSize: '26px'
}
}
}
myChart.setOption(option)
}
// const data = [150, 230, 224, 218, 135, 147, 260]
const data = []
init(data)该方案的原理是在图表上叠加一个额外图层,用于显示“暂无数据”的提示文本。此方式同样支持展示图片,具有较高的灵活性,因此个人倾向于认为这是最佳的解决方案。
补充说明:graphic配置项的手册参考
至此,关于Echarts实现暂无数据的三种方法介绍完毕。如需了解更多相关技巧,建议查阅本站历史文章或继续浏览后续内容,感谢大家的支持!