vue3中创建音频标签,并可以通过点击切换不同的icon图标,实现暂停和播放
时间: 2024-02-24 13:56:20 浏览: 191
可以通过以下步骤实现:
1. 在Vue3组件中创建一个音频标签,如下所示:
```
<template>
<div>
<audio ref="audio" :src="audioSrc"></audio>
<i :class="playIcon" @click="togglePlay"></i>
</div>
</template>
```
2. 在data中定义音频文件的路径和播放状态:
```
<script>
export default {
data() {
return {
audioSrc: 'audio.mp3',
isPlaying: false
}
},
...
}
</script>
```
3. 在methods中定义togglePlay方法,根据当前播放状态来切换播放和暂停,并更新图标:
```
methods: {
togglePlay() {
const audio = this.$refs.audio
this.isPlaying = !this.isPlaying
if (this.isPlaying) {
audio.play()
} else {
audio.pause()
}
}
},
computed: {
playIcon() {
return this.isPlaying ? 'pause-icon' : 'play-icon'
}
}
```
4. 在样式中定义播放和暂停的图标:
```
<style>
.play-icon:before {
content: '播放';
}
.pause-icon:before {
content: '暂停';
}
</style>
```
这样,通过点击图标即可实现音频的播放和暂停,同时图标也会相应地切换。
阅读全文
相关推荐

















