Skip to content

onElementRemoval

类别
导出体积
上次更改
2 weeks ago

当该元素或包含该元素的任何元素被移除时触发。

示例

demo1: recreate new element

removed times: 0

demo2: reuse same element

target element
removed times: 0

用法

vue
<script setup lang="ts">
import { onElementRemoval } from '@vueuse/core'
import { ref } from 'vue'

const btnRef = ref<HTMLElement | null>(null)
const btnState = ref(true)
const removedCount = ref(0)

function btnOnClick() {
  btnState.value = !btnState.value
}

onElementRemoval(btnRef, () => ++removedCount.value)
</script>

<template>
  <button
    v-if="btnState"
    @click="btnOnClick"
  >
    recreate me
  </button>
  <button
    v-else
    ref="btnRef"
    @click="btnOnClick"
  >
    remove me
  </button>
  <b>removed times: {{ removedCount }}</b>
</template>

类型声明

typescript
export interface OnElementRemovalOptions
  extends ConfigurableWindow,
    ConfigurableDocumentOrShadowRoot,
    WatchOptionsBase {}
/**
 * Fires when the element or any element containing it is removed.
 *
 * @param target
 * @param callback
 * @param options
 */
export declare function onElementRemoval(
  target: MaybeElementRef,
  callback: (mutationRecords: MutationRecord[]) => void,
  options?: OnElementRemovalOptions,
): Fn

源码

源码演示文档

贡献者

一纸忘忧
Ben Lau

更新日志

v12.3.0 on 1/2/2025
08cf5 - feat: new function, refactor useActiveElement useElementHover (#4410)