vue实现类似淘宝快递
实现类似淘宝快递跟踪功能
在Vue中实现类似淘宝的快递跟踪功能,需要结合物流信息展示、时间轴组件和API数据交互。以下是关键实现方法:
数据获取与处理 通过第三方物流API(如快递鸟、快递100)获取物流信息,返回的数据通常包含物流节点数组。需要将原始数据转换为适合前端展示的结构。
// 示例数据结构
{
"status": "在途",
"traces": [
{
"time": "2023-05-01 14:00",
"station": "北京市朝阳区网点",
"action": "已收件"
},
// 更多节点...
]
}
时间轴组件实现 使用Vue的列表渲染和条件样式实现时间轴效果。关键点在于当前状态的视觉突出显示。
<template>
<div class="express-track">
<div v-for="(item, index) in traces" :key="index"
:class="['trace-item', { 'active': index === currentActive }]">
<div class="dot"></div>
<div class="content">
<p>{{ item.action }}</p>
<p>{{ item.station }}</p>
<p>{{ item.time }}</p>
</div>
</div>
</div>
</template>
样式设计 CSS实现时间轴的视觉连线效果和状态区分:
.express-track {
position: relative;
padding-left: 20px;
}
.trace-item {
position: relative;
padding-bottom: 20px;
}
.dot {
width: 12px;
height: 12px;
border-radius: 50%;
background: #ccc;
position: absolute;
left: -26px;
top: 4px;
}
.trace-item.active .dot {
background: #FF5000;
box-shadow: 0 0 0 2px rgba(255,80,0,0.2);
}
.trace-item:not(:last-child)::after {
content: '';
position: absolute;
left: -20px;
top: 16px;
height: 100%;
width: 2px;
background: #e0e0e0;
}
状态映射与显示 将API返回的状态码转换为用户友好的文字说明:
const statusMap = {
'0': '在途',
'1': '揽收',
'2': '疑难',
'3': '签收',
'4': '退签',
'5': '派件',
'6': '退回'
}
API请求封装 使用axios封装物流查询请求:
async function queryExpress(companyCode, expressNo) {
try {
const res = await axios.post('/api/express', {
company: companyCode,
number: expressNo
})
return res.data
} catch (error) {
console.error('物流查询失败', error)
return null
}
}
组件封装与复用 将物流跟踪功能封装为可复用组件:
export default {
props: {
expressInfo: {
type: Object,
required: true
}
},
computed: {
traces() {
return this.expressInfo.traces || []
},
currentActive() {
return this.traces.length - 1
}
}
}
优化与扩展 实现自动刷新功能,定期更新物流状态:
mounted() {
this.timer = setInterval(this.fetchData, 300000) // 5分钟刷新一次
},
beforeDestroy() {
clearInterval(this.timer)
}
添加物流公司logo显示,增强用户体验:
<img :src="`/static/express/${expressInfo.companyCode}.png`"
:alt="expressInfo.companyName">
以上实现方案涵盖了从数据获取到界面展示的完整流程,可根据实际需求进行调整和扩展。







