原理: 轮询或websocket接收服务器返回的数据,当请求有新的消息数据返回时,我们就播放一段MP3
<script>
import music from '@/assert/music.mp3' //引入音乐文件
mounted(){
//轮询获取服务器数据
window.setInterval(() => {
this.onHaveInform()
}, 10_000);
},
methods:{
//请求
async onHaveInform() {
let res = await postData(`url`);
if (res.type === 'success') {
if (res.data.new != 0) {
this.playMusic() //有新数据,播放音乐
}
this.inform = res.data.new
}
},
playMusic() {
const audio = new Audio(music);
audio.addEventListener('canplaythrough', () => {
audio.play();
});
}
},
</script>