createMessage代码为什么这么写

来源:10-3 createMessage 第一部分编码

独自灿烂

2025-02-27

老师这是您的代码

import { render, h } from 'vue'
import type { MessageProps } from './types'
import MessageConstructor from './Message.vue'
export const createMessage = (props: MessageProps) => {
  const container = document.createElement('div')
  const vnode = h(MessageConstructor, props)
  render(vnode, container)
  //非空断言操作符
  document.body.appendChild(container.firstElementChild!)
}

这个代码的逻辑是

  • 创建一个div,
  • 创建虚拟dom渲染到div上
  • 把div的第一个元素加到body上
    那为什么不直接把虚拟dom加到body上,这样直接就搞定了啊,老师这么做是有什么考虑么
export const createMessage = (props: MessageProps) => {
  const vnode = h(Message, props)
  render(vnode, document.body)
}

这是我的代码,也是能达到一样的效果啊

写回答

1回答

张轩

2025-03-06

同学你好

为什么使用中间容器而不直接渲染到 body

1 DOM 清理更容易:

- 使用中间容器可以更容易地移除组件。当消息需要消失时,可以直接移除那个特定的元素,而不需要担心影响 body 中的其他内容。

2 避免覆盖 body 内容:

- 直接在 document.body 上渲染会替换 body 的所有内容,而使用 appendChild 只是添加新元素。


3 多个消息实例的管理:

- 当需要显示多个消息时,每个消息都有自己的容器,便于单独控制和移除。


4. Vue 卸载机制:

- 当组件需要被卸载时,使用中间容器可以调用 render(null, container) 来正确清理 Vue 组件实例。


0
0

进阶必学,打造媲美ElementPlus的组件库

Vue3.3 + TS4 ,自主打造媲美 ElementPlus 的组件库

481 学习 · 219 问题

查看课程