vue实现悬浮列表
Vue 实现悬浮列表的方法
使用 CSS 固定定位
通过 CSS 的 position: fixed 属性实现悬浮效果。适用于需要固定在页面某个位置的列表。
<template>
<div class="floating-list">
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
]
}
}
}
</script>
<style>
.floating-list {
position: fixed;
right: 20px;
bottom: 20px;
background: white;
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>
使用 Vue 指令实现拖拽悬浮
通过自定义指令实现拖拽功能,使列表可以自由移动。

<template>
<div v-draggable class="floating-list">
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
</div>
</template>
<script>
export default {
directives: {
draggable: {
mounted(el) {
el.style.position = 'fixed';
el.style.cursor = 'move';
let offsetX, offsetY;
el.addEventListener('mousedown', (e) => {
offsetX = e.clientX - el.getBoundingClientRect().left;
offsetY = e.clientY - el.getBoundingClientRect().top;
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', stop);
});
function move(e) {
el.style.left = `${e.clientX - offsetX}px`;
el.style.top = `${e.clientY - offsetY}px`;
}
function stop() {
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', stop);
}
}
}
},
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
]
}
}
}
</script>
<style>
.floating-list {
background: white;
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>
使用第三方库实现高级悬浮
借助第三方库如 vuedraggable 实现更复杂的拖拽和悬浮功能。
安装库:

npm install vuedraggable
使用示例:
<template>
<draggable v-model="items" class="floating-list">
<template #item="{ element }">
<li>{{ element.text }}</li>
</template>
</draggable>
</template>
<script>
import draggable from 'vuedraggable';
export default {
components: { draggable },
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
]
}
}
}
</script>
<style>
.floating-list {
position: fixed;
right: 20px;
bottom: 20px;
background: white;
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>
响应式悬浮列表
根据滚动位置动态显示或隐藏悬浮列表。
<template>
<div v-if="showList" class="floating-list">
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
],
showList: false
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeUnmount() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
this.showList = window.scrollY > 200;
}
}
}
</script>
<style>
.floating-list {
position: fixed;
right: 20px;
bottom: 20px;
background: white;
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>






