// EmojiUtils.js
export default class EmojiUtils {
static imageIsExist (url) {
return new Promise((resolve) => {
let img = new Image()
img.onload = function () {
if (this.complete === true) {
resolve(true)
img = null
}
}
img.onerror = function () {
resolve(false)
img = null
}
img.src = url
})
}
}
// main.js
import Vue from 'vue'
import EmojiUtils from '@/utils/EmojiUtils'
// 全局注册自定义指令,用于判断当前图片是否能够加载成功,可以加载成功则赋值为img的src属性,否则使用默认图片
Vue.directive('default-img', async function (el, binding) { // 指令名称为:default-img
let needLoadDefault = binding.value // 获取图片地址
if (needLoadDefault) {
let imgURL = el.getAttribute('src')
if (imgURL) {
let exist = await EmojiUtils.imageIsExist(imgURL)
if (exist) {
el.setAttribute('src', imgURL)
} else {
el.setAttribute('src', '/static/img/x.png')
}
} else {
el.setAttribute('src', '/static/img/x.png')
}
}
})
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。