为什么render h函数不能直接使用组件名称在Vue3.x中渲染为Vue2.x

  • 本文关键字:Vue2 Vue3 组件 render 函数 不能 vuejs3
  • 更新时间 :
  • 英文 :


Vue2.x中,代码可以工作;

import Vue from 'vue';
Vue.component('helloworld', {
render(h) {
return h('div', 'this is helloworld');
}
});
new Vue({
el: '#app',
render: h => h('helloworld')
});

但在下面这样的Vue3.x代码中,它无法工作;

import {createApp, h} from 'vue';
const app = createApp({
render: () => h('helloworld')
});
app.component("helloworld", {
render() {
return h('div', 'this is helloworld');
}
});

为什么h('helloworld')可以在vue2中工作,但不能在vue3.x中工作

使用resolveComponent处理组件名称。

你能试着这样使用它吗
在设置中,如他们的文档中所述

import { h, reactive } from 'vue'
export default {
setup(props, { slots, attrs, emit }) {
const state = reactive({
count: 0
})
function increment() {
state.count++
}
// return the render function
return () =>
h(
'div',
{
onClick: increment
},
state.count
)
}
}

我认为这是因为组件没有在"h〃;作用调用的h((与creatApp创建的应用程序是分开的。

在Vue 3中,您必须直接使用resolveComponent()而不是组件字符串。将其弹出到变量中,并按以下使用

import {createApp, h, resolveComponent} from 'vue';
const helloWorldComponent = resolveComponent('helloworld');
const app = createApp({
render: () => h('helloworld')
});

最新更新