vue中img标签404错误处理事件onerror
第一部分:vue中img标签onerror事件第一种方法:使用@error方法能处理onerror事件(据说会导致回闪,目前没遇到)<img :src="xxx图片资源" @error="fn">//当图片资源加载报错404时会被调用fn(e) {//substitute为导入进来的图片e.target.src = this.substitute},//若是真的遇到了回闪@error=
·
以下为图片链接失效的情况
若服务上的图片直接在浏览器上可以打开,但是在img上报404错误处理方法
在index.html中添加代码如下
<meta name="referrer" content="no-referrer" />
第一部分:vue中img标签onerror事件
第一种方法:使用@error方法能处理onerror事件(据说会导致回闪,目前没遇到)
<img :src="xxx图片资源" @error="fn">
//当图片资源加载报错404时会被调用
fn(e) {
//substitute为导入进来的图片
e.target.src = this.substitute
},
//若是真的遇到了回闪 @error=>:onerror
<img :src="xxx图片资源" :onerror="fn">
第二种方法:自定义事件处理onerror事件
第一步:封装一个组件xxxx.js
// 设置按需导出
export const picdirectives = {
//inserted会在当前的dom元素插入到节点之后执行
//el为当前自定义指令的dom
//binding指令中的变量的解释:有一个属性叫做 value,能获取到指令变量
inserted(el, binding) {
//当图片报错404触发
el.onerror = () => {
// 若是截取到了图片报错404的信息,自定义属性触发
//在页面我设置binding.value为本地图片资源,当axios获取到的资源无法获取时就加载本地资源
el.src = binding.value
}
}
}
第二步:在页面的img标签设置自定义指令
//img标签设置自定义指令
<img v-picdirectives="substitute" :src="xxxaxios资源路径">
//导入本地img图片
import bc from '@/assets/common/bc.svg'
//data中定义自定义属性的变量substitute
data() {
return {
substitute: bc
}
},
第三步:导入并使用自定义指令
//导入写到的自定义指令模块xxx.js
import { picdirectives } from '@/directives'
//使用自定义指令
directives: { picdirectives },
扩展:第二种封装自定义指令还可以在vue中设置全局自定义指令
//第一种注册全局自定义指令写法
// 当图片有路迳,没有资源的时候就会报错:404。
imageerror为定义的自定义指定事件名
Vue.directive('imageerror', {
inserted(el, binding) {
// 当图片有错误时候抓取报错,标签.onerror,抓取到报错触发函数
el.onerror = function() {
el.src = binding.value
}
}
})
//第二种注册全局自定义指令写法
//下面是注册所有的自定义指令的写法
//导入所有自定义指令事件模块
import * as directives from '@/directives'
Object.keys(directives).forEach(k => {
Vue.directive(k, directives[k])
})
// 全局自定义指令结束
更多推荐
已为社区贡献8条内容
所有评论(0)