vue3 portal
时间: 2023-10-02 17:03:54 浏览: 59
Vue 3 introduced the new feature called "Portal" which allows you to render a component's content in a different part of the DOM tree, outside of its parent component. This is particularly useful when you want to render a component's content in a different position within the DOM hierarchy.
To use portals in Vue 3, you need to install the `@vue/portal-vue` package. You can do this by running the following command:
```
npm install @vue/portal-vue
```
Once installed, you can import the `Portal` component from the package and use it in your Vue components. Here's an example of how you can use portals:
```vue
<template>
<div>
<button @click="togglePortal">Toggle Portal</button>
<portal to="destination">
<p>This content will be rendered in a different part of the DOM tree.</p>
</portal>
<div id="destination"></div>
</div>
</template>
<script>
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';
import { createSSRApp } from 'vue';
export default {
name: 'MyComponent',
methods: {
togglePortal() {
this.$portal.show('destination');
},
},
};
</script>
```
In this example, we have a button that toggles the visibility of the portal content. The portal content is wrapped inside the `<portal>` component and it has a `to` prop that specifies the ID of the destination DOM element where the content should be rendered. In this case, the destination element is a `<div>` with the ID "destination".
When the button is clicked, the `togglePortal` method is called, which uses the `$portal` instance property to show or hide the portal content in the specified destination.
Note that portals are particularly useful when you want to render modals, tooltips, or any other content that needs to be rendered outside of the current component's DOM hierarchy.