Skip to content

useTransition

值之间的转换

¥Transition between values

示例

Cubic bezier curve: 0.00

Custom function: 0.00

Vector: [0.00, 0.00]

Non-numeric value: Hello

用法

¥Usage

定义一个要跟踪的源值,当值发生变化时,输出将转换为新值。如果在转换过程中源发生变化,则新的转换将从前一个转换被中断的位置开始。

¥Define a source value to follow, and when changed the output will transition to the new value. If the source changes while a transition is in progress, a new transition will begin from where the previous one was interrupted.

ts
import { 
TransitionPresets
,
useTransition
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
source
=
shallowRef
(0)
const
output
=
useTransition
(
source
, {
duration
: 1000,
easing
:
TransitionPresets
.
easeInOutCubic
,
})

可以使用 三次贝塞尔曲线 自定义过渡缓动。

¥Transition easing can be customized using cubic bezier curves.

ts
useTransition
(source, {
easing
: [0.75, 0, 0.25, 1],
})

通过 TransitionPresets 常量可以实现以下转换。

¥The following transitions are available via the TransitionPresets constant.

对于更复杂的缓动,可以提供自定义函数。

¥For more complex easing, a custom function can be provided.

ts
function 
easeOutElastic
(
n
) {
return
n
=== 0
? 0 :
n
=== 1
? 1 : (2 ** (-10 *
n
)) *
Math
.
sin
((
n
* 10 - 0.75) * ((2 *
Math
.
PI
) / 3)) + 1
}
useTransition
(source, {
easing
:
easeOutElastic
,
})

默认情况下,source 必须是一个数字或数字数组。对于更复杂的值,定义一个自定义 interpolation 函数。例如,以下代码将转换 Three.js 的旋转。

¥By default the source must be a number, or array of numbers. For more complex values, define a custom interpolation function. For example, the following would transition a Three.js rotation.

ts
import { 
Quaternion
} from 'three'
const
source
=
ref
(new
Quaternion
())
const
output
=
useTransition
(
source
, {
interpolation
: (
q1
,
q2
,
t
) => new
Quaternion
().slerpQuaternions(
q1
,
q2
,
t
)
})

要控制转换何时开始,请设置 delay 值。要围绕转换编排行为,请定义 onStartedonFinished 回调。

¥To control when a transition starts, set a delay value. To choreograph behavior around a transition, define onStarted or onFinished callbacks.

ts
useTransition
(source, {
delay
: 1000,
onStarted
() {
// called after the transition starts },
onFinished
() {
// called after the transition ends }, })

要停止转换,请定义一个布尔值 disabled 属性。请注意,这与 duration0 不同。禁用的转换同步跟踪源值。它们不尊重 delay,也不触发 onStartedonFinished 回调。

¥To stop transitioning, define a boolean disabled property. Be aware, this is not the same a duration of 0. Disabled transitions track the source value synchronously. They do not respect a delay, and do not fire onStarted or onFinished callbacks.

为了获得更多控制,可以通过 transition 函数手动执行转换。此函数返回一个承诺,在转换完成时解析。可以通过定义返回真值的 abort 函数来取消手动转换。

¥For even more control, transitions can be executed manually via the transition function. This function returns a promise that resolves when the transition is complete. Manual transitions can be cancelled by defining an abort function that returns a truthy value.

ts
import { 
transition
} from '@vueuse/core'
await
transition
(source, from, to, {
abort
() {
if (shouldAbort) return true } })