[vue] beforeDestroy中dom为null?

场景:页面支持播放语音 跳转到其他页面时 需要在 beforeDestroy中暂停播放 防止部分型号手机再下个页面中继续播放

先来看一下代码:

beforeDestroy() {
      let _audio = document.getElementById('audioIntroduce');
      console.log(_audio);
      _audio.pause();
      this.isPlaying = false;
}

结果如下:

通过 document.getElementById('audioIntroduce') 拿到的dom竟然为null?这不科学

接着我在 beforeDestroy() 里打印 document 发现打印出来的document对象竟然是我跳转之后的页面对象QAQ

打断点发现 一旦开始执行 beforeDestroy() 这个方法 页面就跳转到了下一个页面 此时document对象当然就是下一个页面

尝试打印this对象 发现打印出来的this是当前页面的vue对象,那么既然可以拿到当前页面的this对象 同样的 可以通过ref拿到我们想要的audio元素

修改后:

beforeDestroy() {
      let _audio = this.$refs.audioIntroduce;
      console.log(_audio);
      _audio.pause();
      this.isPlaying = false;
}

此时拿到的audio对象:

 yeah!done!!

猜你喜欢

转载自www.cnblogs.com/yan89/p/11514357.html
今日推荐