监听yAxis的数据是否发生变化
data() {
return {
orgList: [],
chart: null
}
},
watch: {
orgList(newOrgList) {
// 当 orgList 变化时,手动触发 dataZoom 事件
if (this.chart) {
this.chart.setOption({
yAxis: {
data: newOrgList // 更新 yAxis 数据
}
})
this.triggerDataZoom() // 手动触发 dataZoom 更新
}
}
},
保存 chart 对象以便在其他方法中使用(this.chart = chart)
Chart1() {
// 计算文本的像素长度
function getTextWidth(text, font) {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
context.font = font
const metrics = context.measureText(text)
return metrics.width
}
const chart = echarts.init(document.getElementById('chart-dynamic-accountability')) // 获取DOM元素并初始化图表对象
const options = {
tooltip: {
trigger: 'item',
formatter(params) {
const xAxisCategory = options.xAxis.data[params.value[0]] // X轴的文本
const yAxisCategory = options.yAxis.data[params.value[1]] // Y轴的文本
const value = params.value[2] // 数据值
return ` ${yAxisCategory}-${xAxisCategory}: ${value}条`
}
},
grid: {
left: 150 // 初始边距
},
xAxis: {
type: 'category',
position: 'top',
data: ['受理', '初核', '分类处置', '核查', '处理', '整改落实', '销号'] // X轴分类数据
},
yAxis: {
type: 'category',
data: this.orgList // Y轴集团数据
},
dataZoom: [
{
type: 'slider',
orient: 'vertical',
showDataShadow: false,
start: 100,
end: 80 // 根据可视区域所能展示的数据量进行调整
}
],
series: [{
type: 'scatter',
data: this.EchartsData,
symbolSize(data) {
return Math.sqrt(data[2]) * 10 // 根据数据量调整点大小
},
label: {
show: true,
formatter(param) {
return param.value[2] // 显示数据值
}
}
}]
}
chart.setOption(options) // 将配置项应用到图表上
this.chart = chart
chart.on('click', (params) => {
this.$emit('getList', { link: params['data'][0] + 1 })
})
// 监听 dataZoom 的 zoom 事件
chart.on('dataZoom', this.handleDataZoom)
},
计算宽度
handleDataZoom(params) {
const { chart } = this
const zoom = chart.getModel().getOption().dataZoom[0]
const totalYAxisData = chart.getModel().getOption().yAxis[0].data.length
const startIndex = Math.floor(totalYAxisData * zoom.start / 100)
const endIndex = Math.ceil(totalYAxisData * zoom.end / 100) - 1
const displayedData = chart.getModel().getOption().yAxis[0].data.slice(startIndex, endIndex + 1)
let maxLength = 0
displayedData.forEach((data) => {
const currentLength = data.toString().length
if (currentLength > maxLength) {
maxLength = currentLength
}
})
const newLeft = maxLength * 12 + 20 // 假设每个字符宽度为 12px,加 20px 留白
chart.setOption({
grid: {
left: `${newLeft}px` // 更新 left 值
}
})
},
triggerDataZoom() {
console.log('ajskdf')
// 手动触发 dataZoom 事件
if (this.chart) {
const zoom = this.chart.getModel().getOption().dataZoom[0]
this.chart.dispatchAction({
type: 'dataZoom',
start: zoom.start,
end: zoom.end
})
}
}