Vue 做任何事情的方式都是使用 VDOM 和 vnode,因此您只需创建一个可以返回其插槽的组件,然后将该插槽用作功能组件:
<template>
<div>
<copy ref="$copy">
<div id="container">
<button @click="handleClick">Click me</button>
</div>
</copy>
<div id="clip"><component :is="clip"/></div>
<button @click="clip = () => $copy.getSlot()()">Copy Content</button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import Copy from './Copy.vue';
const clip = ref(null);
const $copy = ref();
function handleClick() {
alert('click')
}
</script>
复制.vue
<script setup>
import {useSlots} from 'vue';
const slots = useSlots();
defineExpose({
getSlot(name = 'default'){
return slots[name];
}
});
</script>
<template>
<slot />
</template>
功能性方法:
<template>
<div>
<copy>
<div id="container">
<button @click="handleClick">Click me</button>
</div>
</copy>
<div id="clip"><component :is="clip"/></div>
<button @click="clip = () => vnode">Copy Content</button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
let vnode;
const Copy = (_, {slots}) => vnode = slots.default();
const clip = ref(null);
const $copy = ref();
function handleClick() {
alert('click')
}
</script>