Vue3 监听数据更新使div滚动到底部的实现(聊天框场景)


参考

  • vue中watch不触发、不生效的解决办法及原理
  • vue-$nextTick-等待页面渲染完毕的回调

起因

最近在做一个聊天功能,通过 ref 钩子绑定页面实现滚动底部后出现滚动不到底部的情况,猜测是页面未更新完毕的时候,就将 div 滚动到之前状态的底部。

代码

  1. html 容器代码, .message-container 容器需要有具体高度。
    	.message-container {
    	  height: calc(100% - 191px);
    	  padding: 10px 24px;
    	  position: relative;
    	  background-color: #fbfcfe;
    	  overflow-y: auto;
    	}
    
  2. 通过 watch 监听数据更新,并等待页面加载完毕后滚动到 div 底部。
     data() {
    	return {
    	  messages: [
    		{
    		  type: "text",
    		  isMe: false,
    		  content: "你好,我是夏秋初。",
    		}
    	  ],
    	  content: "",
    	};
      },
      watch: {
    	messages: {
    	  handler(newVal, oldName) {
    		/**
    		 * 页面更新完毕后再将页面滚动到底部
    		 */
    		this.$nextTick(() => {
    		  this.$refs.messageContainer.scrollTop =
    			this.$refs.messageContainer.scrollHeight;
    		});
    	  },
    	  deep: true,
    	  immediate: false,
    	},
      },
    
vue