<script setup>
import {reactive,watch,onMounted,onUnmounted, nextTick} from 'vue'
import { useThrottleFn } from '@vueuse/core'

const props=defineProps({
    html:{
        type:String
    }
})

const listState=reactive({
    totalList:[],//分割好的html数组
    totalPage:0,//总页数
    list:[],
    page:0,
    pageSize:20,
})

function loadContent(){
    listState.list = listState.list.concat(listState.totalList.slice(listState.page*listState.pageSize, (listState.page + 1)*listState.pageSize))
}

const load=useThrottleFn(()=>{
    if(listState.page>=listState.totalPage) return
    const clientHeight = document.documentElement.clientHeight || document.body.clientHeight; // 可视高度
    const scrollHeight = document.body.scrollHeight; // 总高度
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 滚动的高度
    // console.log(clientHeight,scrollHeight);
    const bufferHeight = 600;

    if((scrollHeight - scrollTop - clientHeight) < bufferHeight) {
        console.log('触底')
        listState.page ++;
        loadContent();
    }
},300)


watch(
    ()=>props.html,
    (n)=>{
        
        const arr = props.html.split('</p>');
        listState.totalList = arr.map(_ => _+'</p>');
        listState.list = listState.totalList.slice(0,listState.pageSize)
        listState.totalPage =  parseInt(listState.totalList.length / listState.pageSize) + 1;
    },
    {
        immediate:true
    }
)

onMounted(()=>{
    window.addEventListener('scroll',load)
})
onUnmounted(()=>{
    window.removeEventListener('scroll',load)
})


</script>

<template>
    <div v-for="item in listState.list" :key="item" v-html="item"></div>
</template>

<style lang="scss" scoped>

</style>