Skip to content

useClamp

类别
导出大小
223 B
@vueuse/math
最近修改
2 days ago

反应式性地将一个值钳位在两个其他值之间。

🌐 Reactively clamp a value between two other values.

示例

min: max: value:0

用法

🌐 Usage

ts
import { 
useClamp
} from '@vueuse/math'
const
min
=
shallowRef
(0)
const
max
=
shallowRef
(10)
const
value
=
useClamp
(0,
min
,
max
)

可写引用

🌐 Writable Ref

当你传入一个可变的 ref 时,返回的值是一个 可写计算属性,在设置值时会进行限制:

🌐 When you pass a mutable ref, the returned value is a writable computed that clamps values when setting:

ts
import { 
useClamp
} from '@vueuse/math'
const
number
=
shallowRef
(0)
const
clamped
=
useClamp
(
number
, 0, 10)
clamped
.
value
= 15 // clamped.value will be 10
clamped
.
value
= -5 // clamped.value will be 0

只读模式

🌐 Read-only Mode

当你传递一个 getter 函数或只读 ref 时,返回的值是只读的计算属性:

🌐 When you pass a getter function or readonly ref, the returned value is a read-only computed:

ts
import { 
useClamp
} from '@vueuse/math'
const
value
=
ref
(5)
const
clamped
=
useClamp
(() =>
value
.
value
* 2, 0, 10)
// clamped.value is computed from the getter

反应界限

🌐 Reactive Bounds

所有参数(value, min, max)都可以是响应式的:

🌐 All arguments (value, min, max) can be reactive:

ts
import { 
useClamp
} from '@vueuse/math'
const
value
=
shallowRef
(5)
const
min
=
shallowRef
(0)
const
max
=
shallowRef
(10)
const
clamped
=
useClamp
(
value
,
min
,
max
)
max
.
value
= 3 // clamped.value automatically becomes 3