1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import Vue from 'vue'
import { defaultImage } from '@/components/Upload/utils/default'
const getImageSize = function (src) {
return new Promise((resolve, reject) => {
const img = new window.Image()
if (img.complete) {
resolve(img)
}
img.onload = function () {
resolve(img)
}
img.src = src
img.crossOrigin = '*'
img.onerror = function (e) {
reject(e)
}
})
}
const image = {
bind (el, binding) {
},
inserted (el, binding) {
Vue.nextTick(() => {
let style = el.getBoundingClientRect()
let outRatio = style.width / style.height
getImageSize(binding.value).then(res => {
let width = res.width
let height = res.height
let inRatio = width / height > outRatio ? 'height' : 'width'
if (binding.value) {
el.style.backgroundImage = `url(${binding.value})`
}
if (inRatio === 'height') {
el.style.backgroundSize = '100% auto'
} else {
el.style.backgroundSize = 'auto 100%'
}
}).catch(() => {
el.style.backgroundImage = `url(${defaultImage})`
el.style.backgroundSize = '100%'
})
})
},
update (el, binding) {
Vue.nextTick(() => {
let style = el.getBoundingClientRect()
let outRatio = style.width / style.height
getImageSize(binding.value).then(res => {
let width = res.width
let height = res.height
let inRatio = width / height > outRatio ? 'height' : 'width'
if (binding.value) {
el.style.backgroundImage = `url(${binding.value})`
}
if (inRatio === 'height') {
el.style.backgroundSize = '100% auto'
} else {
el.style.backgroundSize = 'auto 100%'
}
}).catch(() => {
el.style.backgroundImage = `url(${defaultImage})`
el.style.backgroundSize = '100%'
})
})
}
}
export default image