Vue的VNode有没有办法动态生成dom?

我使用vue的CreateElement动态生成VNode对象,这个Vnode是作为props参数传递给某个组件的,组件内有没有办法将Vnode渲染成dom,插入到指定的html位置上?

阅读 5.2k
2 个回答

如果你用的是 vue3,有个 render 的方法:

import { render } from 'vue'

render(vnode, el) // el 就是 Element 对象

--- 补充 ---

Vue2(未验证,不行不要打我,vue2 好久没用了):

const CompConstructor = Vue.extend(Comp) // Comp.vue
const instance = new CompConstructor({ el: document.createElement('div') })

// 或者用 new Vue() 的形式创建

instance.$slots.default = [vnode]
target.appendChild(instance.$el)

扔 render 函数不就可以了

比如说 messageBox 组件也是支持直接传入一个 VNode

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题