【问题标题】:Vue 3 Teleport for Vue 2Vue 2 的 Vue 3 传送
【发布时间】:2021-05-14 02:19:18
【问题描述】:

在 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 中实现类似的功能?

【问题讨论】:

    标签: javascript vue.js vuejs2 vuejs3 vue-teleport


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-07-17
      • 2021-03-13
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 2022-07-24
      • 2021-09-15
      相关资源
      最近更新 更多