首页 > 其他 > 详细

[vue] beforeDestroy中dom为null?

时间:2019-09-12 18:43:27      阅读:201      评论:0      收藏:0      [点我收藏+]

场景:页面支持播放语音 跳转到其他页面时 需要在 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!!

 

[vue] beforeDestroy中dom为null?

原文:https://www.cnblogs.com/yan89/p/11514357.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!