lazy-html.vue
1.67 KB
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
<template>
<div class="lazy-html">
</div>
</template>
<script>
import {replaceHttp} from 'common/utils';
import Vue from 'vue';
export default {
name: 'LazyHtml',
props: {
value: [String],
lazy: [Boolean]
},
created() {
if (this.value) {
this.$nextTick(() => {
this.renderHtml(this.value, this.lazy);
});
}
},
watch: {
value(val) {
this.renderHtml(val, this.lazy);
}
},
methods: {
renderHtml(value, lazy) {
let html = this.lazyHtmlReplace(value, lazy);
try {
let res = Vue.compile(`<div>${html}</div>`);
let component = new Vue({
render: res.render,
staticRenderFns: res.staticRenderFns
});
component.$mount(this.$el);
} catch (e) {
html = this.lazyHtmlReplace(this.value);
this.$el.innerHTML = html;
}
},
lazyHtmlReplace(html, lazy) {
let renderImgIndex = 5;
return html
.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, (imgHtml, src) => {
if (src.indexOf('?') < 0) {
src += '?imageMogr2/thumbnail/750x/quality/60/interlace/1';
}
if (lazy) {
renderImgIndex--;
}
src = replaceHttp(src);
return (lazy && renderImgIndex < 0) ? `<img v-lazy="'${src}'" />` : `<img src="${src}" />`;
});
}
}
};
</script>
<style>
</style>