使用uniapp实现全局悬浮按钮(可拖动)

1,659 阅读1分钟

效果如下

实现方案

使用uniapp官方组件 movable-area和movable-view

代码解析

  • 在components新建一个xxx.vue组件

  • 重点在于movable-area与movable-view需要分别增加pointer-events: none和pointer-events: auto用于组件事件穿透与恢复组件事件(此处不加会导致引用该组件的父组件无法使用事件)

  • 组件代码如下:

    $all_width: 96rpx; $all_height:96rpx; .movable-area { height: 100vh; width: 750rpx; top: 0; position: fixed; pointer-events: none; //此处要加,鼠标事件可以渗透 .movable-view { width: $all_width; height: $all_height; pointer-events: auto; //恢复鼠标事件 image { width: $all_width; height: $all_height; } } }

组件生成后可mian.js全局挂载,后续不需要每个页面都进行引入

import App from './App'
import Vue from 'vue'
import myHome from '@/components/my_home.vue'		//引入组件

Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
    ...App
})

Vue.component('my-home',myHome)						//进行全局挂载


app.$mount()

全局挂载后可在需要使用的页面使用

<template>
	<view class="content">
        <!--组件引用-->
		<my-home></my-home>

	</view>
</template>