我想迭代TextTrackCueList的元素,该元素基本上是HTML5视频字幕的数组(供引用:https://developer.mozilla.org/en-US/docs/Web/API/TextTrack#Properties)。这是一个简化的代码:

new Vue ({
  el: "#app",
  data() {
    return {
      vid: null,
      track: null,
      cues: []
    }
  },
  mounted() {
    this.vid = this.$refs.vid;
    this.track = this.vid.addTextTrack("captions");
    this.track.mode = "showing";
    this.cues = this.track.cues;
    this.addCue(); //We add just one cue before the list is rendered
  },
  methods: {
    addCue() {
      let i = this.cues.length;
      //The cue just shows during one second
      let cue = new VTTCue(i, i+1, "Caption "+i);
      this.track.addCue(cue);
    }
  }
});
.cues-list {
  float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <video ref="vid" width="50%" src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4" controls></video>
  <div class="cues-list">
    <ul>
      <li v-for="cue in cues">
        {{ cue.text }}
      </li>
    </ul>
    <button @click="addCue">Add cue</button>
  </div>
</div>


如我们所见,添加新提示时,cues列表未更新。我怀疑的原因是我没有使用Vue.js(https://vuejs.org/v2/guide/list.html#Mutation-Methods)覆盖的一种变异方法,因此DOM不会自动更新。确实,我使用TextTrack.addCue()来添加提示,而不是Array.push(),因为TextTrack.cues属性是只读的。是否有解决方法,例如手动更新虚拟DOM的方法?

谢谢您的帮助。

最佳答案

我发现的唯一答案是迫使Vue重新渲染:

addCue() {
  let i = this.cues.length;
  //The cue just shows during one second
  let cue = new VTTCue(i, i+1, "Caption "+i);
  this.track.addCue(cue);
  this.$forceUpdate();
}

09-17 04:03