vue实现引导页面
Vue 实现引导页面的方法
使用第三方库 vue-tour
安装 vue-tour 库:
npm install vue-tour
在 main.js 中引入并注册:
import Vue from 'vue'
import VueTour from 'vue-tour'
Vue.use(VueTour)
require('vue-tour/dist/vue-tour.css')
在组件中使用:
<template>
<v-tour name="myTour" :steps="steps"></v-tour>
</template>
<script>
export default {
data() {
return {
steps: [
{
target: '#element1',
content: '这是第一个引导步骤'
},
{
target: '.element2',
content: '这是第二个引导步骤'
}
]
}
},
mounted() {
this.$tours['myTour'].start()
}
}
</script>
自定义实现引导组件
创建 Guide 组件:
<template>
<div class="guide-mask" v-if="visible">
<div class="guide-content" :style="contentStyle">
<div>{{ content }}</div>
<button @click="next">下一步</button>
</div>
</div>
</template>
<script>
export default {
props: {
steps: Array,
currentStep: Number
},
computed: {
visible() {
return this.currentStep < this.steps.length
},
content() {
return this.steps[this.currentStep].content
},
contentStyle() {
const target = document.querySelector(this.steps[this.currentStep].target)
if (target) {
const rect = target.getBoundingClientRect()
return {
top: `${rect.top + rect.height}px`,
left: `${rect.left}px`
}
}
return {}
}
},
methods: {
next() {
this.$emit('next')
}
}
}
</script>
<style>
.guide-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
z-index: 9999;
}
.guide-content {
position: absolute;
background: white;
padding: 10px;
border-radius: 4px;
}
</style>
在父组件中使用:
<template>
<div>
<Guide :steps="steps" :current-step="currentStep" @next="handleNext" />
<div id="step1">元素1</div>
<div class="step2">元素2</div>
</div>
</template>
<script>
import Guide from './Guide.vue'
export default {
components: { Guide },
data() {
return {
steps: [
{ target: '#step1', content: '这是第一个引导' },
{ target: '.step2', content: '这是第二个引导' }
],
currentStep: 0
}
},
methods: {
handleNext() {
if (this.currentStep < this.steps.length - 1) {
this.currentStep++
} else {
this.currentStep = -1
}
}
}
}
</script>
使用 driver.js 库
安装 driver.js:
npm install driver.js
在组件中使用:
<template>
<button @click="startTour">开始引导</button>
</template>
<script>
import Driver from 'driver.js'
import 'driver.js/dist/driver.min.css'
export default {
methods: {
startTour() {
const driver = new Driver()
driver.defineSteps([
{
element: '#element1',
popover: {
title: '标题1',
description: '内容1',
position: 'bottom'
}
},
{
element: '.element2',
popover: {
title: '标题2',
description: '内容2',
position: 'top'
}
}
])
driver.start()
}
}
}
</script>
实现要点
确保引导元素在 DOM 中已渲染完成后再启动引导 通过 z-index 确保引导层在最上层 考虑移动端适配和响应式布局 提供跳过和上一步的功能选项 引导结束后可能需要设置 localStorage 标记避免重复展示







