具有HTML5音频属性的vuejs

zl2*_*3cn 2 javascript audio html5 vue.js

我正在使用Vuejs制作音频控制面板,我想将currentTime属性绑定到一个computed值,所以我写

  computed: {
    'currentTime': {
      cache: false,
      get: function () {
        return document.getElementById('player').currentTime
      }
    }
  },
Run Code Online (Sandbox Code Playgroud)

这是我的audio标签:

  <audio :src="musicSrc" preload="auto" id="player">
    <p>Your browser does not support the <code>audio</code> element.</p>
  </audio>
Run Code Online (Sandbox Code Playgroud)

我可以得到它ready

  ready () {
    this.player = document.getElementById('player')
  },
Run Code Online (Sandbox Code Playgroud)

我可以控制它 methods

play: function () {
  this.player.play()
},
Run Code Online (Sandbox Code Playgroud)

但是当我{{ currentTime }}在模板中使用时

计算表达式“ currentTime”时出错。

未捕获的TypeError:无法读取null的属性“ currentTime”

San*_*ain 5

对于vue 2.0,引用元素的方式已更改。

在HTML中
<audio ref="audio" controls>

在Vuejs中
this.currentTime = this.$refs.audio.currentTime


小智 4

您应该通过 v-el 注册才能引用它

<audio v-el:audio :src="musicSrc" preload="auto"></audio>

然后通过 $els 属性在 vue 实例中访问它,如下所示

ready: function() {
    this.$els.audio.play();
}
Run Code Online (Sandbox Code Playgroud)

  • 现在是 `ref="audio"` 和 `this.$refs.audio`,对吧? (4认同)