项目场景:
提示:这里简述项目相关背景:
在项目中有时候需要一些功能,比如震动
描述
提示:这里描述项目中遇到的问题:
在移动应用中,震动反馈是提升用户体验的重要方式。uniapp 提供了两种震动方式:
- 短震动:轻微的触感反馈
- 长震动:较强的震动反馈
分析:
提示:这里填写问题的分析:
1. 短震动 (uni.vibrateShort)
- 作用:触发较短时间的震动
- 震动时长:约 15ms
- 适用场景:按钮点击、操作反馈等轻量级交互
javascript
uni.vibrateShort(options: UniNamespace.VibrateShortOptions)
参数说明:
javascript
interface VibrateShortOptions {
success?: () => void // 接口调用成功的回调函数
fail?: (err: any) => void // 接口调用失败的回调函数
complete?: () => void // 接口调用结束的回调函数(调用成功、失败都会执行)
}
2. 长震动 (uni.vibrateLong)
- 作用:触发较长时间的震动
- 震动时长:约 400ms
- 适用场景:游戏结束、重要提示等需要明显震动反馈的场合
javascript
uni.vibrateLong(options: UniNamespace.VibrateLongOptions)
参数说明:
javascript
interface VibrateLongOptions {
success?: () => void // 接口调用成功的回调函数
fail?: (err: any) => void // 接口调用失败的回调函数
complete?: () => void // 接口调用结束的回调函数(调用成功、失败都会执行)
}
3:平台差异说明
| API | App | H5 | 微信小程序 | 支付宝小程序 | 百度小程序 |
|-----|-----|----| ---------- | ------------ | ---------- |
| vibrateShort | √ | x | √ | √ | √ |
| vibrateLong | √ | x | √ | √ | √ |
4:注意事项
权限要求:
- App 平台需要在 manifest.json 中配置 vibrate 权限
- 部分平台可能需要用户授权
- 使用场景:
- 短震动适合用于轻量级的交互反馈
- 长震动建议用于重要提示,避免过度使用影响用户体验
- 兼容性处理:
- 建议添加错误处理逻辑
- 在不支持的平台上需要提供替代方案
实例方案:
提示:这里填写该问题的具体解决方案:
1. 创建震动工具函数
useVibrate.ts 文件
javascript
/**
* 震动工具函数
*/
export function useVibrate() {
// 短震动
const vibrateShort = () => {
uni.vibrateShort({
success: () => {
console.log('短震动成功')
},
fail: (err) => {
console.error('短震动失败:', err)
}
})
}
// 长震动
const vibrateLong = () => {
uni.vibrateLong({
success: () => {
console.log('长震动成功')
},
fail: (err) => {
console.error('长震动失败:', err)
}
})
}
return {
vibrateShort,
vibrateLong
}
}
2:页面中使用
javascript
<template>
<view class="container">
<button @click="handleShortVibrate">短震动</button>
<button @click="handleLongVibrate">长震动</button>
</view>
</template>
<script setup lang="ts">
import { useVibrate } from '@/composables/useVibrate'
const { vibrateShort, vibrateLong } = useVibrate()
const handleShortVibrate = () => {
vibrateShort()
}
const handleLongVibrate = () => {
vibrateLong()
}
</script>