vue audio组件封装 直接调用方法播放音频源码
封装 index.js
index.js源码
import Vue from 'vue' import TzAudio from './audio' let TzInstance let getInstance = function () { if (TzInstance) return TzInstance const vm = new Vue({ data: {}, render (h) { return h(TzAudio, {}) } }) const component = vm.$mount() document.body.appendChild(component.$el) const tzEle = vm.$children[0] TzInstance = { play (type) { // tzEle.type = type tzEle.audioPlay(type) } } return TzInstance } export default { install (Vue, options = {}) { Vue.prototype.$TzAudio = getInstance() } }
组件中使用
<template> <div > <audio ref="audioTag" hidden="true" style="display:none"> </audio> </div> </template>
audio.vue 存放音频文件路径组件
audio.vue源码
<style scoped> .alertMessage { padding: 60px; margin-top: 20px; font-size: 28px; } </style> <template> <div > <audio ref="audioTag" hidden="true" style="display:none"> </audio> </div> </template> <script> import _ from 'lodash' export default { name: 'TzAudio', data () { return { audioSrc: '', audioType: '', audioFile: [ { type: 'fingertime', path: require('@/assets/audio/fingertime.mp3') }, ] } }, methods: { audioPlay (type) { if (type) { this.audioType = type } let obj = _.find(this.audioFile, ['type', this.audioType]) if (obj) { try { this.$refs.audioTag.src = obj.path this.$refs.audioTag.play() } catch (err) { console.log(err) } } } } } </script>
在其他组件中直接使用方法如下
this.$TzAudio.play('音频文件名称')