vue如何实现timeline
Vue 实现 Timeline 的方法
使用第三方库(如 vis-timeline)
安装 vis-timeline 库:
npm install vis-timeline vis-data
在 Vue 组件中使用:
<template>
<div ref="timeline"></div>
</template>
<script>
import { Timeline } from 'vis-timeline';
import 'vis-timeline/styles/vis-timeline-graph2d.css';
export default {
mounted() {
const container = this.$refs.timeline;
const items = [
{ id: 1, content: '事件1', start: '2023-01-01' },
{ id: 2, content: '事件2', start: '2023-02-01' }
];
new Timeline(container, items);
}
};
</script>
自定义实现 Timeline
通过 Vue 组件和 CSS 自定义时间线:
<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.date }}</p>
<p>{{ item.description }}</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ title: '事件1', date: '2023-01-01', description: '描述1' },
{ title: '事件2', date: '2023-02-01', description: '描述2' }
]
};
}
};
</script>
<style>
.timeline {
position: relative;
padding-left: 50px;
}
.timeline-item {
position: relative;
margin-bottom: 30px;
}
.timeline-dot {
position: absolute;
left: -25px;
top: 0;
width: 20px;
height: 20px;
border-radius: 50%;
background: #42b983;
}
.timeline-content {
padding: 10px;
border-left: 2px solid #42b983;
}
</style>
使用 Vuetify 的 v-timeline 组件
如果项目使用 Vuetify,可以直接使用内置组件:
<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: [
{ title: '事件1', date: '2023-01-01', description: '描述1', color: 'red' },
{ title: '事件2', date: '2023-02-01', description: '描述2', color: 'blue' }
]
};
}
};
</script>
使用 Element UI 的时间线
如果项目使用 Element UI:
<template>
<el-timeline>
<el-timeline-item
v-for="(item, index) in items"
:key="index"
:timestamp="item.date"
>
{{ item.content }}
</el-timeline-item>
</el-timeline>
</template>
<script>
export default {
data() {
return {
items: [
{ date: '2023-01-01', content: '事件1' },
{ date: '2023-02-01', content: '事件2' }
]
};
}
};
</script>
每种方法适用于不同的场景和需求,第三方库提供更丰富的功能,自定义实现更灵活,UI 框架内置组件则更简单易用。







