vue2中this.$createElement()在vue3中应该如何改造
在 Vue2 中,this.$createElement()(或简写 h)是运行时编译器注入的函数,用来手动创建 VNode。
在 Vue3 中,组件选项式 API 不再自动注入 h,需要显式引入;而在 <script setup>
中则直接可用 h。
✅ Vue3 的等效写法
场景 | Vue2 写法 | Vue3 写法(推荐) |
---|---|---|
渲染函数 | render(h) { return h('div') } | import { h } from 'vue' 后直接使用 h |
选项式 API | this.$createElement() | import { h } from 'vue' 并显式使用 |
<script setup> | 无 | 直接 h(...) 即可(自动编译注入) |
Vue2(旧代码)
export default {methods: {createVNode() {return this.$createElement('div', { class: 'box' }, 'hello');},},
};
Vue3(改造后)
import { h } from 'vue';export default {methods: {createVNode() {return h('div', { class: 'box' }, 'hello');},},
};
示例:<script setup>
的写法
<script setup>
import { h } from 'vue';const vnode = h('div', { class: 'box' }, 'hello');
</script>