当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Vue.js watchEffect()用法及代码示例

立即运行一个函数,同时响应地跟踪它的依赖关系,并在依赖关系发生变化时重新运行它。

类型

function watchEffect(
  effect: (onCleanup: OnCleanup) => void,
  options?: WatchEffectOptions
): StopHandle

type OnCleanup = (cleanupFn: () => void) => void

interface WatchEffectOptions {
  flush?: 'pre' | 'post' | 'sync' // default: 'pre'
  onTrack?: (event: DebuggerEvent) => void
  onTrigger?: (event: DebuggerEvent) => void
}

type StopHandle = () => void

细节

第一个参数是要运行的效果函数。效果函数接收可用于注册清理回调的函数。清理回调将在下一次重新运行效果之前调用,可用于清理无效的副作用,例如待处理的异步请求(参见下面的示例)。

第二个参数是一个可选的选项对象,可用于调整效果的刷新时间或调试效果的依赖关系。

返回值是一个句柄函数,可以调用它来阻止效果再次运行。

示例

const count = ref(0)

watchEffect(() => console.log(count.value))
// -> logs 0

count.value++
// -> logs 1

副作用清理:

watchEffect(async (onCleanup) => {
  const { response, cancel } = doAsyncWork(id.value)
  // `cancel` will be called if `id` changes
  // so that previous pending request will be cancelled
  // if not yet completed
  onCleanup(cancel)
  data.value = await response
})

停止观察者:

const stop = watchEffect(() => {})

// when the watcher is no longer needed:
stop()

选项:

watchEffect(() => {}, {
  flush: 'post',
  onTrack(e) {
    debugger
  },
  onTrigger(e) {
    debugger
  }
})

相关用法


注:本文由纯净天空筛选整理自vuejs.org大神的英文原创作品 watchEffect()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。