Appearance
useScroll 页面滚动(vue3)
- 监听页面滚动,获取当前滚动距离,判断是否到顶部,底部,左边,右边,
- 设置滚动坐标,设置滚动模式,设置偏移量
基础使用
vue
<script setup lang="ts">
import { useScroll } from '@mid-vue/shared'
const el = ref<HTMLElement | null>(null)
// arrivedState 判断是否到顶部,底部,左边,右边
// directions 方向
const { x, y, isScrolling, arrivedState, directions } = useScroll(el)
</script>
<template>
<div ref="el" />
</template>偏移 offset
js
const { x, y, isScrolling, arrivedState, directions } = useScroll(el, {
offset: { top: 30, bottom: 30, right: 30, left: 30 },
})设置滚动坐标
Set the x and y values to make the element scroll to that position.
vue
<script setup lang="ts">
import { useScroll } from '@mid-vue/shared'
const el = ref<HTMLElement | null>(null)
const { x, y } = useScroll(el)
</script>
<template>
<div ref="el" />
<button @click="x += 10">Scroll right 10px</button>
<button @click="y += 10">Scroll down 10px</button>
</template>设置滚动模式
Set behavior: smooth to enable smooth scrolling. The behavior option defaults to auto, which means no smooth scrolling. See the behavior option on window.scrollTo() for more information.
ts
import { useScroll } from '@mid-vue/shared'
const el = ref<HTMLElement | null>(null)
const { x, y } = useScroll(el, { behavior: 'smooth' })
// Or as a `ref`:
const smooth = ref(false)
const behavior = computed(() => (smooth.value ? 'smooth' : 'auto'))
const { x, y } = useScroll(el, { behavior })Scroll 返回值
| 名字 | 描述 | 类型 | Default |
|---|---|---|---|
| x | x 轴坐标 | Ref<Number> | '' |
| y | y 轴坐标 | Ref<Number> | '' |
| isScrolling | 是否滚动中 | false | null |
| arrivedState | 是否触边 | left, right , top ,bottom | null |
| directions | 滚动方向 | left, right , top ,bottom | null |
