介绍
可感知元素尺寸的变化,在元素宽度或高度变化时触发事件。
引入
js
import ResizeSensor from 'sard-uniapp/components/resize-sensor/resize-sensor.vue'代码演示
基础使用
将 ResizeSensor 组件放置在要监听尺寸变化的元素里面,此元素需要设置相对、绝对或固定定位;监听 resize 事件,此事件会在被监听元素尺寸发生变化时触发。
vue
<template>
<sar-list card style="margin-bottom: 20rpx">
<sar-list-item title="宽度">
<template #value>
<sar-slider v-model="width" style="width: 560rpx" />
</template>
</sar-list-item>
<sar-list-item title="高度">
<template #value>
<sar-slider v-model="height" style="width: 560rpx" />
</template>
</sar-list-item>
<sar-list-item>
<view
class="box"
:style="{
width: width + '%',
height: height + 'px',
}"
>
<sar-resize-sensor @resize="onResize" />
</view>
</sar-list-item>
<sar-list-item>
<view>width: {{ size?.width }}</view>
<view>height: {{ size?.height }}</view>
</sar-list-item>
</sar-list>
</template>
<script setup lang="ts">
import { type Size } from 'sard-uniapp'
import { ref } from 'vue'
const width = ref(50)
const height = ref(50)
const size = ref<Size>()
const onResize = (value: Size) => {
size.value = value
}
</script>
<style lang="scss" scoped>
.box {
position: relative;
height: 100px;
background-color: var(--sar-primary);
}
</style>vue
<template>
<sar-list card style="margin-bottom: 20rpx">
<sar-list-item title="宽度">
<template #value>
<sar-slider v-model="width" style="width: 560rpx" />
</template>
</sar-list-item>
<sar-list-item title="高度">
<template #value>
<sar-slider v-model="height" style="width: 560rpx" />
</template>
</sar-list-item>
<sar-list-item>
<view
class="box"
:style="{
width: width + '%',
height: height + 'px',
}"
>
<sar-resize-sensor @resize="onResize" />
</view>
</sar-list-item>
<sar-list-item>
<view>width: {{ size?.width }}</view>
<view>height: {{ size?.height }}</view>
</sar-list-item>
</sar-list>
</template>
<script setup lang="js">
import { ref } from "vue";
const width = ref(50);
const height = ref(50);
const size = ref();
const onResize = (value) => {
size.value = value;
};
</script>
<style lang="scss" scoped>
.box {
position: relative;
height: 100px;
background-color: var(--sar-primary);
}
</style>API
ResizeSensorProps
| 属性 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| root-class | 组件根元素类名 | string | - |
| root-style | 组件根元素样式 | StyleValue | - |
| threshold | 触发 resize 事件的阈值,单位毫秒 | number | 150 |
ResizeSensorEmits
| 事件 | 描述 | 类型 |
|---|---|---|
| resize | 在元素宽或高发生变化时触发 | (value: Size) => void |
Size
ts
interface Size {
height: number
width: number
}