vue3 h5进入页面后自动滚动到底部

背景:

在做h5项目中的聊天页面时,需求是进入页面自动滚到底部,方便用户看到最新消息(因为消息是正序排列的,最新消息自然展示在底部)。

 直接上代码:

<script setup>
import { onMounted, ref, nextTick, watch} from 'vue';
import { getMyQuestionDetail} from "@/api/order.js";

const questionForm = ref({});
/**
 * 查看记录
 */
const getMyQuestion = async () => {
  const { data } = await getMyQuestionDetail({questionCode, answerOrderBy: "ASC"})
  questionForm.value = data
};

/**
 * 滚动到底部
 */
const scrollToBottom = () => {
  nextTick(() => {
    const child = document.querySelector(`#main`) // 需要滚动的元素
    window.scrollTo({
      top: child.scrollHeight ,
      behavior: "smooth"
    })
  })
}
// 数据拿到后开启滚动,以防scrollHeight为0, 不滚动
watch(questionForm, () => {
  scrollToBottom()
})

onMounted(() => {
  getMyQuestion()
});

</script>

<template>
  <div id="main">
    <!-- 记录内容 -->
  </div>
  
  <div class="submit">
      <!-- 固定在页面底部的提交按钮 -->
  </div>
</template>

主要代码:

const child = document.querySelector(`#main`) // 需要滚动的元素
window.scrollTo({
  top: child.scrollHeight ,
  behavior: "smooth"
})

猜你喜欢

转载自blog.csdn.net/qq_58340302/article/details/129859139