vue--如何监听div里面的内容,当到达div底部时,自动向上滚动


先说需求:
数据实时更新渲染到页面
页面高度随数据更新变化
默认页面显示当前更新内容即滚动条处于页面最底部
当用户进行鼠标滚轮向上滚动或者拖动滚动条向上时停止滚动条处于页面最底部操作
当用户进行上一步操作后又向下滚动时 继续让滚动条保持最下
思路:
首先得监听页面的scroll时间并判断是向上或者向下滚动
让滚动条保持在页面最底部

 data() {
        return {
            oldScrollTop:0,
            scrollFlag:true,
            Intervall:null,
        }
    },
   mounted() {
           this.getUpdataData()
           //监听滚动事件
        document.querySelector(".box").addEventListener('scroll',this.scrolling)
        
        this.scrollToBottom();
    },
      destroyed(){
          // 销毁监听滚动事件
         document.querySelector(".consoleBox").removeEventListener('scroll',this.scrolling)
    },
methods:{
    //滚动条保持最底部方法
    scrollToBottom () {
            this.$nextTick(() => {
                var container = this.$el.querySelector(".box");
                container.scrollTop = container.scrollHeight;
            })
        },
        
        scrolling() {
            let scrollTop = document.querySelector(".box").scrollTop 
            // 更新——滚动前,滚动条距文档顶部的距离
            let scrollStep = scrollTop - this.oldScrollTop;
            this.oldScrollTop = scrollTop;
            //判断当前是向上or向下滚动
            if (scrollStep < 0) {
                //向上
                console.log("正在向上滚动")
                this.scrollFlag=false
            }else{
            console.log("正在向下滚动")
                this.scrollFlag=true
            } 
        },
        getUpdataData(){
                    //定时获取后台返回数据
                     this.Interval=setInterval(()=>{
                           ajax("/xxx/xxx/xx").then(res=>{
                            //更新数据
                            this.xxx=res.data
                            //当数据更新完毕清除定时器
                            if(res.code===0){
                                clearInterval(this.Interval)
                            }
                            })
                            //调用保持滚动条方法(这一步也可以在updated生命周期调用)
                        if(this.scrollFlag){
                                    this.scrollToBottom();
                           }
                   },1000)
        }
}

原文地址:https://blog.csdn.net/weixin_54410967/article/details/121974459

web