useMotionValueEvent

useMotionValueEvent管理 Vue 组件生命周期中的运动值事件处理器。

<script setup lang="ts">
import { useMotionValue } from 'motion-v'

const x = useMotionValue(0)

useMotionValueEvent(x, 'animationStart', () => {
  console.log('animation has started')
})
</script>

<template>
  <Motion
    style:="{ x }"
  />
</template>

当组件卸载时,事件处理器将被安全清理。

使用

从 Motion Vue 导入:

import { useMotionValueEvent } from 'motion-v'

为运动值添加事件监听器,请提供值、事件名称和回调函数:

const color = useMotionValue('#00f')

useMotionValueEvent(color, 'change', (latest) => {
  console.log(latest)
})

可用事件包括:

  • 更改
  • animationStart
  • 动画完成
  • animationCancel

change 事件提供运动值的最新值。

高级

useMotionValueEvent 是用于运动值 on 方法 的辅助函数。使用 on,您可以在任何时候开始监听事件,例如在事件处理程序中。但请记住,当组件卸载时也要取消订阅。

function doSomething() {}

const color = useMotionValue('#00f')
const unsub = color.on('change', doSomething)

onUnmounted(() => {
  unsub()
})