vue实现步骤条功能
Vue 实现步骤条功能
使用 Element UI 的 Steps 组件
安装 Element UI 库并引入 Steps 组件:
npm install element-ui
在 Vue 文件中使用 Steps 组件:
<template>
<el-steps :active="active" finish-status="success">
<el-step title="步骤1" description="描述信息"></el-step>
<el-step title="步骤2" description="描述信息"></el-step>
<el-step title="步骤3" description="描述信息"></el-step>
</el-steps>
</template>
<script>
export default {
data() {
return {
active: 0
}
}
}
</script>
通过修改 active 的值可以控制当前步骤,结合按钮实现步骤切换:
<el-button @click="next">下一步</el-button>
<script>
export default {
methods: {
next() {
if (this.active++ > 2) this.active = 0
}
}
}
</script>
自定义步骤条组件
创建一个基础的步骤条组件:
<template>
<div class="steps">
<div
v-for="(step, index) in steps"
:key="index"
:class="['step', { 'active': currentStep === index }]"
>
{{ step.title }}
</div>
</div>
</template>
<script>
export default {
props: {
steps: Array,
currentStep: Number
}
}
</script>
<style>
.steps {
display: flex;
justify-content: space-between;
}
.step {
padding: 10px;
border: 1px solid #ccc;
}
.step.active {
background: #409EFF;
color: white;
}
</style>
在父组件中使用:
<template>
<custom-steps :steps="steps" :current-step="currentStep"/>
<button @click="currentStep = (currentStep + 1) % steps.length">下一步</button>
</template>
<script>
export default {
data() {
return {
steps: [
{ title: '第一步' },
{ title: '第二步' },
{ title: '第三步' }
],
currentStep: 0
}
}
}
</script>
动态内容切换
结合步骤条实现内容切换效果:
<template>
<div>
<!-- 步骤条 -->
<custom-steps :steps="steps" :current-step="currentStep"/>
<!-- 动态内容 -->
<div v-if="currentStep === 0">
第一步内容
</div>
<div v-else-if="currentStep === 1">
第二步内容
</div>
<div v-else>
第三步内容
</div>
<!-- 导航按钮 -->
<button @click="prev" :disabled="currentStep === 0">上一步</button>
<button @click="next" :disabled="currentStep === steps.length - 1">下一步</button>
</div>
</template>
<script>
export default {
methods: {
prev() {
this.currentStep--
},
next() {
this.currentStep++
}
}
}
</script>
状态保存
使用 Vuex 管理步骤状态:
// store.js
export default new Vuex.Store({
state: {
currentStep: 0,
steps: ['step1', 'step2', 'step3']
},
mutations: {
NEXT_STEP(state) {
state.currentStep++
},
PREV_STEP(state) {
state.currentStep--
}
}
})
组件中调用:
<template>
<button @click="$store.commit('NEXT_STEP')">下一步</button>
</template>






