所以我需要使用Howler.js播放一些mp3音频,并需要一个最小的GUI。我创建了一个按钮组件,该组件将根据播放器的状态显示“播放”或“暂停”图标。这是代码:
<template>
<div><button class="ui icon button" @click="toggleAudioPlay">
<i v-if="isPlaying" class="pause icon"></i>
<i v-else class="play icon"></i>
</button>
<button @click="showDuration">Show</button>
</div>
</template>
<script lang="ts">
import { Howl } from 'howler'
export default {
props: ['audio'],
data: function () {
return {
player: null
}
},
computed: {
isPlaying () {
console.log('updating "isPlaying"')
return this.player && this.player.playing()
}
},
methods: {
toggleAudioPlay () {
if (!this.player) {
this.player = new Howl({
src: [this.audio]
})
}
if (this.isPlaying) {
this.player.pause()
} else {
this.player.play()
}
},
showDuration () {
console.log('Duration is:', this.player ? this.player.duration() : 0)
}
}
}
</script>
<style>
</style>
这是codeandbox上的running example以上代码。
它按预期工作。但是考虑了一下之后,我开始怀疑它为什么起作用:isPlaying
不仅取决于this.player
的值,还取决于this.player
的内部状态,Vue如何知道何时重新计算计算出的属性isPlaying
?
我在函数isPlaying
中添加了日志记录语句,以查看属性何时更新。测试表明它已更新
this.player
从null
更改了); play
或{{1}之后}方法,播放器仍然是同一播放器,只是pause
方法的结果已更改)。调用任何播放器方法后,Vue都会重新检查播放器状态吗?
我添加了playing
按钮,以调用播放器的show
方法,该方法不会更改播放器的播放状态。使用此按钮进行的测试表明,调用duration
时isPlaying
未被更新,因此看起来Vue确切知道播放器的哪些方法将改变其状态。这让我感到惊讶,因为从技术上讲,任何方法都可以改变玩家的状态,因此您必须阅读/分析代码以确定它是否会改变玩家的状态。实际上,Howler.js播放器的duration
方法非常复杂,而不仅仅是查询播放器的属性。
我在Reactivity in Depth上检查了Vue的文档,找不到与此相关的任何内容。
对任何相关说明或对Vue的相关文档或代码的引用表示赞赏。