用vue 写h5页面-摇一摇

  vue配合其他ui框架除了开发一个完整的web项目外,也有不少的项目做一些h5的活动页面开发。你的页面现在需要模拟微信的摇一摇动作。

  项目环境: vue-cli 完成的一个项目

  准备插件(包):依赖的第三方的插件(后续会完成如何写vue插件的方法)shake.js ,github地址: https://github.com/alexgibson/shake.js 我使用的github 项目要点赞(现在要养成习惯)

  使用:在vue的一个组件里使用这个 插件。

  接下来我们看这个插件提供的api,灵不灵照书行。

  shake.js 到是没有提供一个完成的 vue 使用的demo api ,现在要尝试使用这个

  安装包: npm install shake.js --save

  使用包

  

  基本上是按照api 文档上来搬的代码。我们在摇一摇的时候,处理发出声音并振动。

  查看我们的摇一摇的结果:

  因为在pc 上无法完成我们的摇一摇,所以要在手机上查看。在一个局域网下,发送可以访问自己电脑的ip给你的 小 phone,然后就是使劲的要吧。 顺便提供一个摇一摇的声音下载地址: http://sc.chinaz.com/yinxiao/

  附件:本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>