主题
onElementRemoval
当该元素或包含该元素的任何元素从 DOM 中移除时触发。
🌐 Fires when the element or any element containing it is removed from the DOM.
示例
demo1: recreate new element
removed times: 0
demo2: reuse same element
target elementremoved times: 0
用法
🌐 Usage
vue
<script setup lang="ts">
import { onElementRemoval } from '@vueuse/core'
import { shallowRef, useTemplateRef } from 'vue'
const btnRef = useTemplateRef('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>带有变更记录的回调
🌐 Callback with Mutation Records
回调会接收一个触发移除的 MutationRecord 对象数组。
🌐 The callback receives an array of MutationRecord objects that triggered the removal.
ts
import { onElementRemoval } from '@vueuse/core'
onElementRemoval(targetRef, (mutationRecords) => {
console.log('Element removed', mutationRecords)
})返回值
🌐 Return Value
返回一个用于停止观察的停止函数。
🌐 Returns a stop function to stop observing.
ts
const stop = onElementRemoval(targetRef, callback)
// Later, stop observing
stop()