<template>
    <div id="v-scrol" class="v-scrol-text">
        <div class="v-scrol-text-container">
            <div id="v-scrol-text1">
                <ul>
                    <li v-for="item in datas">
                        <span>{{ item }}</span>
                    </li>
                </ul>
            </div>
            <div id="v-scrol-text2"></div>
        </div>
    </div>
</template>

<script>
    export default {
        name:'v-scroll-text',
        props: {
            scrollData: {
                type: Array,
                default: [],
            },
            scrolWidth: {
                type:Number
            }
        },
        data () {
            return {
                datas: null
            }
        },
        watch: {
            scrollData (val) {
                this.datas = val;
                this.scroll();
            }
        },
        methods: {
            scroll () {
                let self = this;
                self.$nextTick(function () {
                    let parentEle = document.getElementById("v-scrol");
                    let childEle = document.getElementById("v-scrol-text1");
                    let copyChildEle = document.getElementById("v-scrol-text2");
                    copyChildEle.innerHTML= childEle.innerHTML;
                    console.log('aa');
                    // 当组件父元素的宽度大于childEle的宽度的时候，组件只会滚动一次，不会连续滚动, 所以这时需要给数据复制成双份。
                    if (self.scrolWidth && self.scrolWidth > childEle.offsetWidth) {
                        self.datas = self.datas.concat(self.datas);
                        self.scroll();
                    } else {
                        function Marquee() {
                            if(parentEle.scrollLeft - copyChildEle.offsetWidth >= 0) {
                                parentEle.scrollLeft -= childEle.offsetWidth;
                            } else {
                                parentEle.scrollLeft++;
                            }
                            // console.log(parentEle.scrollLeft+','+childEle.offsetWidth)
                        }

                        let myvar = setInterval(Marquee, 40);
                        parentEle.onmouseout = function () {
                            myvar = setInterval(Marquee, 40);
                        }
                        parentEle.onmouseover = function () {
                            clearInterval(myvar);
                        }
                    }
                });
            }
        },
        mounted () {
            // 改到watch中实现监听再滚动，以免数据获取慢的情况下不能滚动
            // this.scroll();
        }
    }

</script>
