Vue 可以通过使用 '$mount' 方法来实现 createportal,将组件渲染在指定的 DOM 元素下。

具体步骤如下:

  1. 在组件中添加一个挂载点,用于挂载到指定的 DOM 元素下。
<template>
  <div class='portal-wrapper'></div>
</template>
  1. 在组件的 mounted 生命周期中,使用 $mount 方法将组件挂载到指定的 DOM 元素下。
mounted() {
  const wrapper = document.querySelector('.portal-wrapper');
  const el = document.createElement('div');
  wrapper.appendChild(el);
  this.$mount(el);
}
  1. 将组件渲染在 body 下,可以在根实例中添加一个 portal 组件,并将其挂载到 body 上。
new Vue({
  el: '#app',
  components: {
    Portal: {
      template: '<div></div>',
      mounted() {
        const el = document.createElement('div');
        document.body.appendChild(el);
        this.$mount(el);
      }
    }
  },
  template: '<Portal />'
});

这样,组件就会被渲染在 body 下了。需要注意的是,由于组件被挂载到 body 下,可能会影响到 CSS 样式,需要进行一些额外的调整。

Vue 创建 Portal 组件:将组件渲染到 body 下

原文地址: https://www.cveoy.top/t/topic/lDFD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录