vue实现手机振动
vue实现手机振动的方法
在Vue中实现手机振动功能,可以通过调用浏览器的Vibration API来完成。该API允许控制设备的振动功能,适用于移动浏览器环境。
检查浏览器支持情况
使用前需要检查浏览器是否支持振动API。可以通过以下代码检测:
const isVibrationSupported = 'vibrate' in navigator;
单次振动
触发一次固定时长的振动(单位毫秒):
navigator.vibrate(200);
振动模式
传入数组实现复杂振动模式,例如振动200ms、暂停100ms、再振动300ms:
navigator.vibrate([200, 100, 300]);
停止振动
调用以下方法立即停止所有振动:
navigator.vibrate(0);
Vue组件封装示例
在Vue组件中封装振动功能:
export default {
methods: {
vibrate(pattern) {
if (!('vibrate' in navigator)) {
console.warn('Vibration API not supported');
return;
}
navigator.vibrate(pattern);
},
stopVibration() {
navigator.vibrate(0);
}
}
}
使用注意事项
振动API需要用户手势触发,不能在页面加载时自动执行。通常在点击事件处理函数中调用:

<button @click="vibrate(200)">振动</button>
兼容性说明
大多数现代移动浏览器支持该API,包括Chrome for Android、Firefox for Android和Safari on iOS。建议在使用前进行特性检测。






