vue3悬浮球弹窗
时间: 2025-05-01 16:19:22 浏览: 25
### Vue3 实现悬浮球弹窗组件
#### 创建悬浮球组件 `FloatingBall.vue`
此组件负责创建一个可以拖动并触发弹窗显示的悬浮球。
```vue
<template>
<view class="floating-ball" @touchstart="onTouchStart" @touchmove="onTouchMove">
<image :src="iconSrc"></image>
</view>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const props = defineProps({
iconSrc: {
type: String,
required: true
}
});
let startX = ref(0);
let startY = ref(0);
let currentX = ref(0);
let currentY = ref(0);
function onTouchStart(event) {
const touch = event.touches[0];
startX.value = touch.clientX;
startY.value = touch.clientY;
// 获取初始位置
const ballRect = event.target.getBoundingClientRect();
currentX.value = ballRect.left;
currentY.value = ballRect.top;
}
function onTouchMove(event) {
const touch = event.touches[0];
let deltaX = touch.clientX - startX.value;
let deltaY = touch.clientY - startY.value;
// 更新悬浮球的位置
event.target.style.transform = `translate(${currentX.value + deltaX}px, ${currentY.value + deltaY}px)`;
}
</script>
<style scoped>
.floating-ball {
position: fixed;
bottom: 20px;
right: 20px;
width: 50px;
height: 50px;
background-color: #fff;
border-radius: 50%;
box-shadow: 0 0 10px rgba(0, 0, 0, .2);
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
}
.floating-ball image {
width: 70%;
height: 70%;
}
</style>
```
#### 创建弹窗组件 `PopupWindow.vue`
该组件用于展示当点击悬浮球时出现的内容。
```vue
<template>
<view v-if="visible" class="popup-window">
<!-- 弹窗内容 -->
<slot></slot>
</view>
</template>
<script setup>
import { ref } from 'vue';
defineExpose({ toggleVisibility });
let visible = ref(false);
function toggleVisibility() {
visible.value = !visible.value;
}
</script>
<style scoped>
.popup-window {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background-color: white;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, .1);
z-index: 1000;
}
</style>
```
#### 主应用文件集成
在主应用程序中引入上述两个组件,并设置逻辑使得点击悬浮球能够控制弹窗显隐状态。
```javascript
// main.js 或者 App.vue 中适当的地方
import FloatingBall from './components/FloatingBall.vue';
import PopupWindow from './components/PopupWindow.vue';
export default {
components: {
FloatingBall,
PopupWindow
},
data() {
return {
popupVisible: false
};
},
methods: {
handleTogglePopup() {
this.popupVisible = !this.popupVisible;
}
}
};
```
```html
<!-- 在模板部分 -->
<floating-ball :icon-src="'path/to/icon.png'" @click="handleTogglePopup"/>
<popup-window v-show="popupVisible">这里是弹窗的具体内容。</popup-window>
```
通过这种方式,在uni-app环境中利用Vue3特性实现了具有交互性的悬浮球及其关联的弹窗效果[^1][^2]。为了确保最佳用户体验,建议测试不同设备上的表现,并调整样式以适应特定需求。
阅读全文
相关推荐

















