resource-box.vue 2.88 KB
<template>
    <div class="resource-box">
        <slot></slot>
    </div>
</template>

<script>
import {REPORT_YAS} from 'store/yoho/types';
import _ from 'lodash';
import {mapState} from 'vuex';
import {throttle} from 'common/utils';

export default {
    name: 'ResourceBox',
    data() {
        return {
            componentStatus: {}
        };
    },
    computed: {
        ...mapState(['yoho'])
    },
    watch: {
        ['yoho.pageVisible'](visible) {
            if (visible === 'true' || visible === true) {
                this.checkReport(void 0, true);
            }
        },
        ['yoho.visible'](visible) {
            if (visible && this.$yoho && this.$yoho.isiOS) {
                this.checkReport(void 0, true);
            }
        }
    },
    mounted() {
        this.scrollEvent = throttle(50, this.checkReport);
        if (_.get(this.$parent, '$options.name') === 'Scroller') {
            this.$scrollEl = this.$parent.$el;
        } else {
            this.$scrollEl = document.querySelector('.layout-content');
        }
        if (this.$scrollEl) {
            this.$scrollEl.addEventListener('scroll', this.scrollEvent);
            this.checkReport(void 0, true);
        }
    },
    destroyed() {
        if (this.$scrollEl) {
            this.$scrollEl.removeEventListener('scroll', this.scrollEvent);
        }
    },
    methods: {
        checkReport(evt, isInit) {
            _.each(this.$children, (component, index) => {
                const visiable = this.isVisiable(component.$el, this.$scrollEl);

                if (visiable && (this.componentStatus[index] !== visiable || isInit)) {
                    this.report(component, index + 1);
                }
                this.componentStatus[index] = visiable;
            });
        },
        report(component, index) {
            const reportData = _.get(component, '$options.propsData.value');

            if (reportData) {
                const param = {
                    P_NAME: this.$route.name,
                    F_NAME: reportData.template_name,
                    F_ID: reportData.template_id,
                    F_INDEX: index
                };

                this.$store.dispatch(REPORT_YAS, {
                    params: {
                        appop: 'YB_SHOW_EVENT',
                        param
                    }
                });
            }
        },
        isVisiable($el, $parent) {
            const rect = $el.getBoundingClientRect();
            const parentRect = $parent.getBoundingClientRect();

            return ((parentRect.top >= rect.top && parentRect.top <= (rect.top + rect.height)) ||
                    ((parentRect.top + parentRect.height) >= rect.top && (parentRect.top + parentRect.height) <= (rect.top + rect.height)) ||
                    (rect.top >= parentRect.top && (rect.top + rect.height) <= (parentRect.top + parentRect.height)));
        }
    }
};
</script>