<template>
<view class="container">
<!-- 图表容器 -->
<qiun-data-charts type="line" :chartData="chartData" :opts="chartOptions" @touchmove="handleTouch" />
<!-- 自定义提示框 -->
<view v-if="showToolTip" class="tooltip" :style="{ top: tooltipTop + 'px', left: tooltipLeft + 'px' }">
<view class="tooltip-content">
<view class="tooltip-item">日期:{{ time }}</view>
<view class="tooltip-item" v-for="item in seriesData" :key="item.name">
{{ item.name }}: {{ item.value }}
</view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
// 图表数据
chartData: {
categories: ["1月", "2月", "3月", "4月", "5月", "6月", "7月"],
series: [
{
name: "成交量A",
data: [35, 8, 25, 37, 4, 20, 15]
},
{
name: "成交量B",
data: [70, 40, 65, 100, 44, 68, 50]
},
]
},
// 图表配置项
chartOptions: {
color: ["#1890FF", "#FACC14"],
padding: [15, 15, 0, 15],
legend: {
show: true,
position: "bottom",
float: "center"
},
xAxis: {
disableGrid: true
},
yAxis: {
gridType: "dash",
dashLength: 2
},
extra: {
line: {
type: "curve"
}
}
},
// 提示框状态
showToolTip: false,
time: '', // 日期
seriesData: [], // 系列数据
tooltipTop: 0,
tooltipLeft: 0
};
},
methods: {
// 处理触摸事件
handleTouch(e) {
// 获取触摸点的坐标
const touchX = e.changedTouches[0].pageX;
const touchY = e.changedTouches[0].pageY;
// 使用 wx.createSelectorQuery 获取图表容器的尺寸和位置
const query = wx.createSelectorQuery().in(this);
query.select('.container').boundingClientRect((rect) => {
if (!rect) {
console.error('无法获取图表容器的尺寸和位置');
return;
}
// 获取图表容器的尺寸和位置
const chartWidth = rect.width;
const chartHeight = rect.height;
const chartLeft = rect.left;
const chartTop = rect.top;
// 计算触摸点在图表中的相对位置
const relativeX = touchX - chartLeft;
const relativeY = touchY - chartTop;
// 计算触摸点对应的图表数据索引
const dataLength = this.chartData.series[0].data.length;
const index = Math.floor((relativeX / chartWidth) * dataLength);
// 确保索引在有效范围内
if (index >= 0 && index < dataLength) {
// 获取对应的时间
this.time = this.chartData.categories[index];
// 获取每个系列的数据值
this.seriesData = this.chartData.series.map(series => ({
name: series.name,
value: series.data[index]
}));
// 更新提示框的内容和位置
this.showToolTip = true;
this.tooltipTop = touchY - 20; // 调整提示框位置,使其在触摸点上方
this.tooltipLeft = touchX - 20; // 调整提示框位置,使其在触摸点左侧
}
}).exec();
}
}
};
</script>
<style>
.container {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
position: relative; /* 确保提示框可以相对于容器定位 */
}
.tooltip {
position: absolute;
background-color: rgba(0, 0, 0, 0.7);
color: white;
padding: 5px 10px;
border-radius: 5px;
font-size: 14px;
display: flex;
flex-direction: column; /* 使内容竖着排列 */
}
.tooltip-item {
margin-bottom: 5px; /* 每行之间的间距 */
}
</style>
ucharts写的折线图实现手指滑动根据滑动的位置显示相关的数据信息(vue2写法)
于 2025-02-12 11:15:59 首次发布