<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 setup lang="ts">
import { ref, reactive, getCurrentInstance } from 'vue';
// 获取当前组件实例
const instance = getCurrentInstance();
// 图表数据
const chartData = reactive({
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]
}
]
});
// 图表配置项
const chartOptions = reactive({
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"
}
}
});
// 提示框状态
const showToolTip = ref(false);
const time = ref(''); // 日期
const seriesData = ref([]); // 系列数据
const tooltipTop = ref(0);
const tooltipLeft = ref(0);
// 处理触摸事件
function handleTouch(e: any) {
// 获取触摸点的坐标
const touchX = e.changedTouches[0].pageX;
const touchY = e.changedTouches[0].pageY;
// 使用 wx.createSelectorQuery 获取图表容器的尺寸和位置
const query = wx.createSelectorQuery().in(instance?.proxy);
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 = chartData.series[0].data.length;
const index = Math.floor((relativeX / chartWidth) * dataLength);
// 确保索引在有效范围内
if (index >= 0 && index < dataLength) {
// 获取对应的时间
time.value = chartData.categories[index];
// 获取每个系列的数据值
seriesData.value = chartData.series.map(series => ({
name: series.name,
value: series.data[index]
}));
// 更新提示框的内容和位置
showToolTip.value = true;
tooltipTop.value = touchY - 20; // 调整提示框位置,使其在触摸点上方
tooltipLeft.value = 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写的折线图实现手指滑动根据滑动的位置显示相关的数据信息(vue3写法)
最新推荐文章于 2025-02-14 17:56:07 发布