全局异常捕获:前端资源会出现加载失败问题,如何捕获了? 图片加载失败,如何优化显示错误了?
在vue中:
<script>
mounted() {
//或者指定局部的:this.$refs.div1.addEventListener('error', this.errorEvent, true)
window.addEventListener('error', this.errorEvent, true)
},
beforeDestroy() {
window.removeEventListener('error', this.errorEvent, true)
},
methods: {
errorEvent(e) {
//1.常用的tag有:img link script等
//2.注意这里必须在捕获阶段才能监听到
const tag = e.target.localName
//3.处理图片加载失败后,显示为:加载失败
if (tag === 'img') {
e.target.style = 'font-size:10px'
e.target.alt = '加载失败'
}
},
</script>
标签:target,errorEvent,捕获,tag,html,全局,true,加载
From: https://www.cnblogs.com/charlesxiao/p/17105142.html