跳到主要內容

onElementRemoval

分類
導出大小
上次變更
2 個月前

當元素或包含它的任何元素被移除時觸發。

示範

demo1:重新建立新元素

移除次數:0

demo2:重複使用相同元素

目標元素
移除次數:0

用法

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

const btnRef = useTemplateRef<HTMLElement>('btn')
const btnState = shallowRef(true)
const removedCount = shallowRef(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

原始碼

原始碼示範文件

貢獻者

Anthony Fu
IlyaL
Anthony Fu
Ben Lau

變更日誌

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

根據 MIT 許可證發布。