首先在main.js中导入audio
import audio from "../static/pd-5b768de9060ff779.mp3";
Vue.prototype.clickButton = () => {
let buttonAudio = document.getElementById('buttonAudio');
buttonAudio.setAttribute('src', audio);
buttonAudio.setAttribute('loop','loop');
//重复播放
buttonAudio.play();
//开始播放
}
document.body.addEventListener('click', function(e) {
let event = e || window.event;
let target = event.target || event.srcElement;
let clickMusic = target.getAttribute('clickMusic')
if (clickMusic === 'true') Vue.prototype.clickButton()
else return false;
})
在组件中直接使用
<button @click="play()">播放音乐</button>
<audio src="" id="buttonAudio"></audio>
// 播放音乐
play() {
this.clickButton();
console.log('我发生了点击事件')
},
点击触发play方法,触发全局方法 clickButton();
网友评论