当前位置:首页 > VUE

vue实现手机震动

2026-01-18 02:14:43VUE

Vue 中实现手机震动的方法

在 Vue 项目中可以通过调用浏览器的 Vibration API 实现手机震动功能。以下是具体实现方式:

检测浏览器支持性

在调用震动功能前需检查浏览器是否支持该 API:

vue实现手机震动

const isVibrationSupported = 'vibrate' in navigator;

基本震动实现

调用 navigator.vibrate() 方法触发震动,参数为毫秒数或震动模式数组:

vue实现手机震动

// 单次震动 200ms
navigator.vibrate(200);

// 震动模式:震动200ms,暂停100ms,再震动300ms
navigator.vibrate([200, 100, 300]);

Vue 组件封装示例

<template>
  <button @click="vibrate">点击震动</button>
</template>

<script>
export default {
  methods: {
    vibrate() {
      if (!navigator.vibrate) {
        alert('您的设备不支持震动功能');
        return;
      }

      // 震动模式:短-长-短
      navigator.vibrate([100, 50, 200]);
    }
  }
}
</script>

停止震动

可以通过传递 0 或空数组停止当前震动:

navigator.vibrate(0);
// 或
navigator.vibrate([]);

注意事项

  1. 该 API 需要用户先与页面交互(如点击按钮)后才能触发
  2. iOS 设备普遍不支持此 API
  3. 长时间震动可能被浏览器限制
  4. 建议将震动功能包装在用户交互事件处理器中

兼容性处理

对于不支持原生震动的设备,可以尝试以下 fallback 方案:

function safeVibrate(pattern) {
  if (navigator.vibrate) {
    navigator.vibrate(pattern);
  } else {
    console.warn('Vibration not supported');
    // 可以在此处添加替代反馈,如声音提示
  }
}

响应式封装示例

<template>
  <button @click="triggerVibration">震动反馈</button>
</template>

<script>
export default {
  data() {
    return {
      isSupported: false
    }
  },
  mounted() {
    this.isSupported = 'vibrate' in navigator;
  },
  methods: {
    triggerVibration() {
      if (this.isSupported) {
        navigator.vibrate([30, 50, 30]);
      }
    }
  }
}
</script>

标签: 手机vue
分享给朋友:

相关文章

vue实现tag

vue实现tag

Vue 实现标签(Tag)功能 在 Vue 中实现标签(Tag)功能可以通过多种方式完成,以下是一些常见的方法和实现步骤: 使用动态组件和 v-for 通过 v-for 指令动态渲染标签列表,结合样…

vue实现标签

vue实现标签

Vue 实现标签的方法 在 Vue 中实现标签功能可以通过多种方式完成,以下是几种常见的方法: 使用动态组件 动态组件可以根据不同的条件渲染不同的标签内容。通过 :is 属性动态绑定组件名,实现标签…

vue轮播实现

vue轮播实现

Vue 轮播实现方法 使用第三方库(推荐) 安装 swiper 或 vue-awesome-swiper 库,快速实现功能丰富的轮播效果。 以 vue-awesome-swiper 为例: npm…

vue实现抽屉

vue实现抽屉

Vue 实现抽屉组件 抽屉组件是一种常见的 UI 模式,通常用于从屏幕边缘滑出内容。以下是几种实现抽屉的方法: 使用 Vue 原生实现 创建一个基本的抽屉组件,利用 Vue 的过渡和条件渲染功能。…

vue sku 实现

vue sku 实现

Vue SKU 实现方案 在电商系统中,SKU(Stock Keeping Unit)是商品的最小库存单位,通常由多个属性组合而成(如颜色、尺寸等)。以下是基于 Vue 的实现方案。 数据结构设计…

vue排他思想实现

vue排他思想实现

Vue 排他思想实现 排他思想在 Vue 中通常指多个元素中只能有一个被选中或激活的状态。可以通过数据驱动和条件渲染实现。 使用 v-model 和计算属性 定义一个数据属性存储当前选中项的索引或标…