vue3 teleport
时间: 2023-09-12 09:08:30 浏览: 125
Vue 3 introduced a new feature called "teleport" which allows you to render a component's content at a different place in the DOM hierarchy. It is useful when you want to render a component's content outside of its current DOM container, such as rendering a modal dialog at the end of the document body.
To use teleport in Vue 3, you need two elements: the source element and the target element. The source element is where you define the content that you want to teleport, and the target element is where you want to render that content.
Here's an example of how to use teleport in Vue 3:
```vue
<template>
<div>
<button @click="showModal = true">Open Modal</button>
<teleport to="body">
<Modal v-if="showModal" @close="showModal = false">
<!-- Modal content here -->
</Modal>
</teleport>
</div>
</template>
<script>
import { ref } from 'vue';
import Modal from './Modal.vue';
export default {
components: {
Modal,
},
setup() {
const showModal = ref(false);
return {
showModal,
};
},
};
</script>
```
In this example, we have a button that triggers the modal to appear. The `teleport` component wraps the `Modal` component, and the `to` attribute specifies the target element where the modal should be rendered (in this case, the `<body>` element).
When the `showModal` variable is set to `true`, the modal will be rendered inside the target element specified by `teleport`.
Please note that the `teleport` component requires a build of Vue 3 with teleport support (Vue 3.0.5 or later).
阅读全文