vue如何实现timeline
Vue 实现 Timeline 的方法
使用第三方库(如 vue-timeline)
安装 vue-timeline 库:
npm install vue-timeline --save
在组件中引入并使用:
<template>
<timeline>
<timeline-item v-for="(item, index) in items" :key="index">
{{ item.content }}
</timeline-item>
</timeline>
</template>
<script>
import { Timeline, TimelineItem } from 'vue-timeline';
export default {
components: {
Timeline,
TimelineItem
},
data() {
return {
items: [
{ content: '事件 1' },
{ content: '事件 2' },
{ content: '事件 3' }
]
};
}
};
</script>
自定义实现 Timeline
通过 CSS 和 Vue 动态渲染实现自定义 Timeline:
<template>
<div class="timeline">
<div v-for="(item, index) in items" :key="index" class="timeline-item">
<div class="timeline-dot"></div>
<div class="timeline-content">
<h3>{{ item.title }}</h3>
<p>{{ item.description }}</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ title: '事件 1', description: '描述内容 1' },
{ title: '事件 2', description: '描述内容 2' },
{ title: '事件 3', description: '描述内容 3' }
]
};
}
};
</script>
<style>
.timeline {
position: relative;
padding-left: 20px;
}
.timeline-item {
position: relative;
padding-bottom: 20px;
}
.timeline-dot {
position: absolute;
left: -10px;
top: 0;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #42b983;
}
.timeline-content {
margin-left: 30px;
}
.timeline-item:not(:last-child)::after {
content: '';
position: absolute;
left: 0;
top: 20px;
height: 100%;
width: 2px;
background-color: #e0e0e0;
}
</style>
使用 Vuetify 的 Timeline 组件
如果项目使用 Vuetify,可以直接使用其内置的 v-timeline 组件:
<template>
<v-timeline>
<v-timeline-item
v-for="(item, index) in items"
:key="index"
:color="item.color"
>
<template v-slot:opposite>
{{ item.date }}
</template>
<v-card>
<v-card-title>{{ item.title }}</v-card-title>
<v-card-text>{{ item.description }}</v-card-text>
</v-card>
</v-timeline-item>
</v-timeline>
</template>
<script>
export default {
data() {
return {
items: [
{ date: '2023-01-01', title: '事件 1', description: '描述内容 1', color: 'red' },
{ date: '2023-02-01', title: '事件 2', description: '描述内容 2', color: 'blue' },
{ date: '2023-03-01', title: '事件 3', description: '描述内容 3', color: 'green' }
]
};
}
};
</script>
动态加载 Timeline 数据
结合 API 动态加载 Timeline 数据:
<template>
<div class="timeline">
<div v-for="(item, index) in timelineData" :key="index" class="timeline-item">
<div class="timeline-dot" :style="{ backgroundColor: item.color }"></div>
<div class="timeline-content">
<h3>{{ item.title }}</h3>
<p>{{ item.description }}</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
timelineData: []
};
},
async created() {
try {
const response = await fetch('https://api.example.com/timeline');
this.timelineData = await response.json();
} catch (error) {
console.error('加载数据失败:', error);
}
}
};
</script>






