vue实现步骤条组件
Vue 步骤条组件实现
基础实现思路
通过动态渲染步骤项和状态控制实现步骤条。核心是利用v-for循环和条件判断样式。
<template>
<div class="steps">
<div
v-for="(step, index) in steps"
:key="index"
class="step-item"
:class="{ 'active': currentStep >= index, 'completed': currentStep > index }"
>
<div class="step-index">{{ index + 1 }}</div>
<div class="step-title">{{ step.title }}</div>
<div class="step-connector" v-if="index < steps.length - 1"></div>
</div>
</div>
</template>
<script>
export default {
props: {
steps: {
type: Array,
required: true
},
currentStep: {
type: Number,
default: 0
}
}
}
</script>
<style scoped>
.steps {
display: flex;
justify-content: space-between;
}
.step-item {
display: flex;
flex-direction: column;
align-items: center;
position: relative;
}
.step-index {
width: 30px;
height: 30px;
border-radius: 50%;
background: #ccc;
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 8px;
}
.step-item.active .step-index {
background: #409eff;
color: white;
}
.step-item.completed .step-index {
background: #67c23a;
color: white;
}
.step-connector {
position: absolute;
top: 15px;
left: calc(50% + 15px);
width: 100%;
height: 2px;
background: #ccc;
}
.step-item.completed + .step-item .step-connector {
background: #67c23a;
}
</style>
可点击交互版本
增加点击事件允许用户跳转到特定步骤。
<template>
<div class="steps">
<div
v-for="(step, index) in steps"
:key="index"
class="step-item"
:class="{
'active': currentStep >= index,
'completed': currentStep > index,
'clickable': clickable
}"
@click="handleStepClick(index)"
>
<!-- 同上 -->
</div>
</div>
</template>
<script>
export default {
props: {
clickable: {
type: Boolean,
default: false
}
},
methods: {
handleStepClick(index) {
if (this.clickable) {
this.$emit('step-click', index);
}
}
}
}
</script>
<style scoped>
.step-item.clickable {
cursor: pointer;
}
</style>
垂直布局实现
通过修改CSS实现垂直步骤条。
.steps.vertical {
flex-direction: column;
height: 100%;
}
.steps.vertical .step-item {
flex-direction: row;
align-items: flex-start;
margin-bottom: 20px;
}
.steps.vertical .step-connector {
position: absolute;
left: 15px;
top: 30px;
width: 2px;
height: calc(100% - 30px);
}
动态内容插槽
使用插槽允许自定义步骤内容。
<template>
<div class="steps">
<div
v-for="(step, index) in steps"
:key="index"
class="step-item"
:class="{ 'active': currentStep >= index }"
>
<slot name="step" :step="step" :index="index">
<!-- 默认内容 -->
<div class="step-index">{{ index + 1 }}</div>
<div class="step-title">{{ step.title }}</div>
</slot>
</div>
</div>
</template>
使用示例
<template>
<Steps
:steps="[
{ title: '第一步' },
{ title: '第二步' },
{ title: '第三步' }
]"
:currentStep="currentStep"
@step-click="handleStepClick"
/>
</template>
<script>
import Steps from './Steps.vue';
export default {
components: { Steps },
data() {
return {
currentStep: 0
}
},
methods: {
handleStepClick(index) {
this.currentStep = index;
}
}
}
</script>
关键实现要点
- 使用
v-for动态渲染步骤项 - 通过
:class绑定控制步骤状态样式 - 使用绝对定位实现连接线
- 通过插槽支持内容自定义
- 提供水平和垂直两种布局方式
- 支持点击交互功能






