主题
useTransition
值之间的转换
¥Transition between values
示例
用法
¥Usage
定义要遵循的数字源值,更改后输出将转换为新值。如果在转换过程中源发生变化,则新的转换将从前一个转换被中断的位置开始。
¥Define a numeric 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,
transition: TransitionPresets.easeInOutCubic,
})
要同步转换,请使用数字数组。作为示例,以下是我们如何在颜色之间进行转换的方法。
¥To synchronize transitions, use an array of numbers. As an example, here is how we could transition between colors.
ts
const source = shallowRef([0, 0, 0])
const output = useTransition(source)
const color = computed(() => {
const [r, g, b] = output.value
return `rgb(${r}, ${g}, ${b})`
})
可以使用三次贝塞尔曲线自定义转场缓动。以这种方式定义的转换与 CSS 缓动函数 的工作方式相同。
¥Transition easing can be customized using cubic bezier curves. Transitions defined this way work the same as CSS easing functions.
ts
useTransition(source, {
transition: [0.75, 0, 0.25, 1],
})
通过 TransitionPresets
常量可以实现以下转换。
¥The following transitions are available via the TransitionPresets
constant.
对于更复杂的转换,可以提供自定义函数。
¥For more complex transitions, 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, {
transition: easeOutElastic,
})
要控制转换何时开始,请设置 delay
值。要围绕转换编排行为,请定义 onStarted
或 onFinished
回调。
¥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
属性。请注意,这与 duration
或 0
不同。禁用的转换同步跟踪源值。它们不尊重 delay
,也不触发 onStarted
或 onFinished
回调。
¥To temporarily 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.
为了获得更多控制,可以使用 executeTransition
手动执行转换。该函数返回一个在完成时解析的 promise。可以通过定义返回真值的 abort
函数来取消手动转换。
¥For more control, transitions can be executed manually by using executeTransition
. This function returns a promise that resolves upon completion. Manual transitions can be cancelled by defining an abort
function that returns a truthy value.
ts
import { executeTransition } from '@vueuse/core'
await executeTransition(source, from, to, {
duration: 1000,
})