vue2 获取 audio 实例
时间: 2023-09-04 08:11:54 浏览: 49
要获取一个 `audio` 元素的实例,在 Vue2 中可以通过以下步骤进行:
1. 在 Vue 组件的 `data` 中定义一个 `audio` 对象,用来存储 `audio` 元素的实例:
```javascript
data() {
return {
audio: null
}
}
```
2. 在 `mounted` 钩子函数中使用 `this.$refs` 获取 `audio` 元素,并将其赋值给 `audio` 对象:
```javascript
mounted() {
this.audio = this.$refs.audio
}
```
3. 在模板中使用 `ref` 属性给 `audio` 元素命名,并在需要的地方引用 `audio` 对象即可:
```html
<template>
<div>
<audio ref="audio" src="audio.mp3"></audio>
<button @click="playAudio">播放</button>
</div>
</template>
<script>
export default {
data() {
return {
audio: null
}
},
mounted() {
this.audio = this.$refs.audio
},
methods: {
playAudio() {
this.audio.play()
}
}
}
</script>
```