vue实现步进器
Vue 实现步进器的方法
使用 Element UI 的 Steps 组件
安装 Element UI 后可以直接使用 Steps 组件实现步进器功能。
<template>
<el-steps :active="active" finish-status="success">
<el-step title="步骤1"></el-step>
<el-step title="步骤2"></el-step>
<el-step title="步骤3"></el-step>
</el-steps>
<el-button @click="next">下一步</el-button>
</template>
<script>
export default {
data() {
return {
active: 0
}
},
methods: {
next() {
if (this.active++ > 2) this.active = 0
}
}
}
</script>
自定义实现步进器
可以通过 v-for 和条件渲染实现自定义步进器。
<template>
<div class="stepper">
<div v-for="(step, index) in steps" :key="index"
:class="['step', { 'active': currentStep === index, 'completed': currentStep > index }]">
<div class="step-number">{{ index + 1 }}</div>
<div class="step-title">{{ step }}</div>
</div>
</div>
<button @click="prevStep" :disabled="currentStep === 0">上一步</button>
<button @click="nextStep" :disabled="currentStep === steps.length - 1">下一步</button>
</template>
<script>
export default {
data() {
return {
steps: ['第一步', '第二步', '第三步'],
currentStep: 0
}
},
methods: {
nextStep() {
if (this.currentStep < this.steps.length - 1) {
this.currentStep++
}
},
prevStep() {
if (this.currentStep > 0) {
this.currentStep--
}
}
}
}
</script>
<style>
.stepper {
display: flex;
justify-content: space-between;
}
.step {
display: flex;
flex-direction: column;
align-items: center;
}
.step.active .step-number {
background: #409EFF;
color: white;
}
.step.completed .step-number {
background: #67C23A;
color: white;
}
.step-number {
width: 30px;
height: 30px;
border-radius: 50%;
background: #ddd;
display: flex;
align-items: center;
justify-content: center;
}
</style>
使用 Vue Router 实现步进导航
结合路由可以实现多页面步进效果。
// router.js
const routes = [
{ path: '/step1', component: Step1 },
{ path: '/step2', component: Step2 },
{ path: '/step3', component: Step3 }
]
// App.vue
<template>
<div>
<router-view></router-view>
<button @click="goPrev" :disabled="$route.path === '/step1'">上一步</button>
<button @click="goNext" :disabled="$route.path === '/step3'">下一步</button>
</div>
</template>
<script>
export default {
methods: {
goPrev() {
const steps = ['/step1', '/step2', '/step3']
const currentIndex = steps.indexOf(this.$route.path)
if (currentIndex > 0) {
this.$router.push(steps[currentIndex - 1])
}
},
goNext() {
const steps = ['/step1', '/step2', '/step3']
const currentIndex = steps.indexOf(this.$route.path)
if (currentIndex < steps.length - 1) {
this.$router.push(steps[currentIndex + 1])
}
}
}
}
</script>
使用第三方库 vue-stepper
安装 vue-stepper 库可以快速实现步进器功能。
npm install vue-stepper
<template>
<stepper :steps="steps" :current-step="currentStep" @step-changed="stepChanged"></stepper>
</template>
<script>
import Stepper from 'vue-stepper'
export default {
components: { Stepper },
data() {
return {
steps: ['第一步', '第二步', '第三步'],
currentStep: 0
}
},
methods: {
stepChanged(step) {
this.currentStep = step
}
}
}
</script>






