uniapp 微信小程序Vue3项目使用内置组件movable-area封装悬浮可拖拽按钮(拖拽结束时自动吸附到最近的屏幕边缘)

一、最终效果

二、具体详情请看movable-areamovable-view官方文档说明

三、组件源码

html 复制代码
<template>
  <movable-area class="movable-area" @touchend="onTouchend">
    <movable-view class="movable-view" :x="x" :y="y" direction="all" @change="onChange">
      <view class="addBtn" @tap="handleClick">{{title}}</view>
      <slot />
    </movable-view>
  </movable-area>
</template>

<script lang="ts" setup>
import { debounce } from "@/utils";
defineProps({
  title: {
    type: String
  }
});
const emits = defineEmits(["click"]);
const x = ref(0);
const y = ref(0);
const screenWidth = ref(0);
const screenHeight = ref(0);

onMounted(() => {
  uni.getSystemInfo({
    success: res => {
      screenWidth.value = res.windowWidth;
      screenHeight.value = res.windowHeight;
      // 初始位置在屏幕右下角
      y.value = screenHeight.value - 200;
      x.value = screenWidth.value - 70;
    }
  });
});
// 拖动坐标更新(防抖)
const onChange = (e: { detail: { x: number; y: number } }) => {
  debounce(() => {
    x.value = e.detail.x;
    y.value = e.detail.y;
  }, 500);
};
// 触摸结束时吸附边缘
const onTouchend = () => {
  nextTick(() => {
    const threshold = 50; // 吸附阈值(rpx)
    if (Math.abs(x.value - 0) < threshold) {
      x.value = 0;
    } else if (Math.abs(x.value - screenWidth.value) < threshold) {
      x.value = screenWidth.value;
    }
    if (Math.abs(y.value - 0) < threshold) {
      y.value = 0;
    } else if (Math.abs(y.value - screenHeight.value) < threshold) {
      y.value = screenHeight.value;
    }
  });
};
const handleClick = () => {
  emits("click");
};
</script>

<style lang="scss">
.movable-area {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: calc(100vh - 100px);
  pointer-events: none; /* 关键样式 */
  z-index: 9999;
  .movable-view {
    pointer-events: auto; /* 关键样式 */
    width: 100rpx;
    height: 100rpx;
    will-change: transform;
    .addBtn {
      border-radius: 50%;
      width: 40px;
      height: 40px;
      overflow: hidden;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
      font-size: 14px;
      padding: 8px;
      box-shadow: 0 1px 5px 2px rgba(0, 0, 0, 0.3);
      background: #355db4;
      text-align: center;
    }
  }
}
</style>

相关文章

基于ElementUi再次封装基础组件文档


vue3+ts基于Element-plus再次封装基础组件文档

相关推荐
十五_在努力14 分钟前
Tailwind Css 中使用 Element Plus 主题系统的方案与实现
前端·vue.js
白雾茫茫丶31 分钟前
Cover Magic:专业的封面设计工具,支持实时预览和高质量导出
vue.js·vite
前端小巷子1 小时前
高性能 Vue 应用运行时策略
前端·vue.js·面试
前端加油站1 小时前
使用 pnpm patch 修改第三方依赖
前端·vue.js
江城开朗的豌豆1 小时前
Element UI表格组件的秘密武器:key属性的妙用与全属性解析
前端·javascript·vue.js
江城开朗的豌豆1 小时前
Vue.js vs 原生开发:为什么我用了Vue就回不去了?
前端·javascript·vue.js
wcy01121 小时前
vue3+vue-flow制作简单可拖拽可增删改流程图
javascript·vue.js·流程图
muyun28006 小时前
History 模式 vs Hash 模式:Vue Router 技术决策因素详解
vue.js·算法·哈希算法
码上暴富9 小时前
axios请求的取消
前端·javascript·vue.js
tager11 小时前
Vue 3 组件开发中的"双脚本"困境
前端·vue.js·代码规范