如何解决Vue 3 Teleport for Vue 2
在 Vue 3 中,可以像这样将组件 Teleport 加入 body
标签:
<template>
<button @click="modalOpen = true">
Open full screen modal! (With teleport!)
</button>
<teleport to="body">
<div v-if="modalOpen" class="modal">
<div>
I'm a teleported modal!
(My parent is "body")
<button @click="modalOpen = false">
Close
</button>
</div>
</div>
</teleport>
</template>
<script>
export default {
data() {
return {
modalOpen: false
}
}
};
</script>
这会导致上面的模态对话在 body
标签中呈现。如何在 Vue 2 中实现类似的功能?
解决方法
由于 Vue 2 不支持传送,我建议使用为 vue 2 制作的 portal-vue 组件:
安装:
npm i portal-vue --save
用法:
main.js
import Vue from "vue"
import PortalVue from 'portal-vue'
Vue.use(PortalVue)
...
在一些子组件中:
<portal to="destination">
<p>This slot content will be rendered wherever the <portal-target> with name 'destination'
is located.</p>
</portal>
在其他地方:
<portal-target name="destination">
<!--
This component can be located anywhere in your App.
The slot content of the above portal component will be rendered here.
-->
</portal-target
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。