vue.js 将组件挂载到应用程序根目录

Mar*_*ton 4 vue.js vuejs2

我有一个 modal.vue 组件,如下所示:

<template>

    <transition name="modal-transition">
        <div class="modal-body" v-if="displayed">
            <div class="modal-overlay" @click="displayed = false"></div>
            <div class="modal-content">
                <slot/>
            </div>
        </div>
    </transition>

</template>
Run Code Online (Sandbox Code Playgroud)

如何将此组件安装到应用程序根元素而不是就位?

对于粗略的不准确的例子:

<body>
  <div id="app">
    <div class="header"></div>
    <div class="nav"></div>
    <div class="stage">
       <div class="sub-nav"></div>
       <div class="content">
          <modal :display.sync="display">MY MODAL</modal> <-- Don't mount here...
       </div>
    </div>
    <-- Mount here instead...
  </div>
</body>
Run Code Online (Sandbox Code Playgroud)

当前的问题是我的网站标题和导航分层在我的模式之上,并且它是变暗的全屏覆盖层,而不是分层在模式覆盖层后面。

标题和导航位于顶部

Con*_*hop 7

Vue 3 更新

现在有一个名为teleport 的内置功能,它允许将组件模板的一部分安装到任何 DOM 元素。

OP 中的示例看起来像这样

<!-- MyModal.vue -->
<template>
    <transition name="modal-transition">
        <div class="modal-body" v-if="displayed">
            <div class="modal-overlay" @click="displayed = false"></div>
            <div class="modal-content">
                <slot/>
            </div>
        </div>
    </transition>
</template>
Run Code Online (Sandbox Code Playgroud)
<!-- SomeDeeplyNestedComponent.vue -->
<template>
    <teleport to="#app">
        <!-- Can still receive props from parent -->
        <MyModal :my-prop="foo">
           <!-- slot content -->
        </MyModal>
    </teleport>
</template>
Run Code Online (Sandbox Code Playgroud)