uniapp scroll-view 怎么通过代码控制滚动到底部

在 uniapp 中,可以通过以下几种方式来控制 scroll-view 滚动到底部:

  1. 使用 scroll-into-view 属性:
<template>
  <scroll-view :scroll-into-view="scrollToView" scroll-y="true">
    <view v-for="(item, index) in list" :key="index" :id="'item-' + index">
      {{ item }}
    </view>
  </scroll-view>
</template>

<script>
export default {
  data() {
    return {
      list: ['Item 1', 'Item 2', 'Item 3'],
      scrollToView: ''
    }
  },
  methods: {
    scrollToBottom() {
      this.scrollToView = 'item-' + (this.list.length - 1)
    }
  }
}
</script>
  1. 使用 scroll-top 属性:
<template>
  <scroll-view :scroll-top="scrollTop" scroll-y="true" @scroll="onScroll">
    <view v-for="(item, index) in list" :key="index">
      {{ item }}
    </view>
  </scroll-view>
</template>

<script>
export default {
  data() {
    return {
      list: ['Item 1', 'Item 2', 'Item 3'],
      scrollTop: 0,
      scrollViewHeight: 0,
      scrollContentHeight: 0
    }
  },
  methods: {
    onScroll(e) {
      this.scrollViewHeight = e.detail.scrollHeight
      this.scrollContentHeight = e.detail.scrollTop + e.detail.scrollHeight
    },
    scrollToBottom() {
      this.scrollTop = this.scrollContentHeight - this.scrollViewHeight
    }
  }
}
</script>
  1. 使用 uni.createSelectorQuery() 方法:
<template>
  <scroll-view class="scroll-view" scroll-y="true">
    <view v-for="(item, index) in list" :key="index">
      {{ item }}
    </view>
  </scroll-view>
</template>

<script>
export default {
  data() {
    return {
      list: ['Item 1', 'Item 2', 'Item 3']
    }
  },
  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this)
        query.select('.scroll-view').boundingClientRect()
        query.selectAll('.scroll-view view').boundingClientRect()
        query.exec(res => {
          const scrollViewHeight = res[0].height
          const scrollContentHeight = res[1].reduce((total, item) => total + item.height, 0)
          const scrollTop = scrollContentHeight - scrollViewHeight
          uni.pageScrollTo({
            scrollTop: scrollTop,
            duration: 300
          })
        })
      })
    }
  }
}
</script>

这些方法都可以实现将 scroll-view 滚动到底部的效果[1][2][4]。选择哪种方法取决于你的具体需求和场景。第一种方法最简单,第二种方法可以更精确地控制滚动位置,第三种方法则更加灵活,可以适应不同的布局情况。

在使用这些方法时,记得在适当的时机调用滚动方法,比如在数据更新后或者在用户触发某个操作后[4]。另外,为了提高性能,可以考虑使用节流函数来控制滚动方法的调用频率[4]。

Citations:
[1] https://tehub.com/a/bPDJwPXyBY
[2] https://www.cnblogs.com/Can-daydayup/p/12006891.html
[3] https://zh.uniapp.dcloud.io/component/scroll-view.html
[4] https://blog.csdn.net/weixin_45559449/article/details/133176963
[5] https://cloud.tencent.com/developer/article/1551513

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值