vue实现悬浮列表
实现悬浮列表的方法
使用 CSS 定位
在 Vue 中实现悬浮列表可以通过 CSS 的 position: fixed 或 position: sticky 属性来控制元素的位置。

<template>
<div class="floating-list">
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
</div>
</template>
<style>
.floating-list {
position: fixed;
top: 20px;
right: 20px;
background: white;
border: 1px solid #ddd;
padding: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
</style>
动态控制悬浮状态
可以通过 Vue 的 v-show 或 v-if 指令动态控制悬浮列表的显示和隐藏。

<template>
<button @click="toggleList">显示/隐藏列表</button>
<div class="floating-list" v-show="isVisible">
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false,
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
]
}
},
methods: {
toggleList() {
this.isVisible = !this.isVisible
}
}
}
</script>
响应式悬浮
结合 Vue 的响应式特性,可以根据滚动位置动态调整悬浮列表的样式。
<template>
<div class="floating-list" :class="{ 'scrolled': isScrolled }">
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
isScrolled: false,
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
]
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
this.isScrolled = window.scrollY > 100
}
}
}
</script>
<style>
.floating-list {
position: fixed;
top: 20px;
right: 20px;
transition: all 0.3s;
}
.floating-list.scrolled {
background: #f5f5f5;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}
</style>
拖拽悬浮列表
通过第三方库如 vuedraggable 实现可拖拽的悬浮列表。
<template>
<div class="floating-list">
<draggable v-model="items" @end="onDragEnd">
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
</draggable>
</div>
</template>
<script>
import draggable from 'vuedraggable'
export default {
components: { draggable },
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
]
}
},
methods: {
onDragEnd() {
console.log('拖拽结束')
}
}
}
</script>






