Vue3复制outerHTML点击事件不起作用

问题描述 投票:0回答:1
vuejs3 outerhtml
1个回答
0
投票

Vue 做任何事情的方式都是使用 VDOM 和 vnode,因此您只需创建一个可以返回其插槽的组件,然后将该插槽用作功能组件:

参见 Vue SFC Playground

<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>

功能性方法:

参见 Vue SFC Playground

<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>
© www.soinside.com 2019 - 2024. All rights reserved.