vue 写h5页面-摇一摇

依赖的第三方的插件 shake.js 

github地址: https://github.com/alexgibson/shake.js  

提供一个摇一摇音效下载地址:http://aspx.sc.chinaz.com/query.aspx?keyword=%E6%91%87%E4%B8%80%E6%91%87&classID=14

安装包shake.js:

   npm install shake.js --save

vue组件内容:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <span @click="toastDemo"> 123</span>
    <h4>手机摇一摇的功能</h4>
    <div>
      <audio src="../../static/5018.wav"  ref="shakeAudio">
        您的浏览器不支持 audio 标签。
      </audio>
    </div>
  </div>
</template>

<script>
// var Shake = require('shake.js'); // commonjs 的方式引入
import Shake from 'shake.js'; // es6的方式导入
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  created () {
  },
  mounted () {
    let myShakeEvent = new Shake({
        threshold: 12, // optional shake strength threshold
        timeout: 500 // optional, determines the frequency of event generation
    });
    myShakeEvent.start();
    window.addEventListener('shake', this.shakeEventDidOccur, false);
  },
  methods: {
    toastDemo () {
      // toastPlugin('你好,npm package')
    },
    shakeEventDidOccur () {
      // alert("it's shake!")
      // myShakeEvent.stop();
      let audio = this.$refs.shakeAudio;
      if (window.navigator.vibrate) {
        navigator.vibrate(500);
      }
      audio.play()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

需要注意的是在微信里面,ios内置的浏览器是没有声音的,这时候需要,引入微信的api,通过他触发声音的播放。

 npm install weixin-js-sdk --save
import wx from 'weixin-js-sdk';
 
使用方法:
<audio id="shakeAudio" :src="/5218.mp3" preload ref="shakeAudio"></audio>
 
methods: {
  palyAudio () {
  window.wx.config({    debug: false,    appId: '',   timestamp: 1,   nonceStr: '',   signature: '',   jsApiList: []   });   window.wx.ready(function () { document.getElementById('shakeAudio').play();   });
}
}

猜你喜欢

转载自www.cnblogs.com/luobiao/p/10552216.html