在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')
});