lazy-html.vue 1.67 KB
<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>