JackieWillen
JackieWillen

Reputation: 739

Why the render h function cannot use component name directly to render in Vue3.x as Vue2.x?

In Vue2.x, the code can work;

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

But in Vue3.x code like below, it can not work;

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

why h('helloworld') can work in vue2, but cannot work in vue3.x

Upvotes: 1

Views: 1027

Answers (4)

SimonHawesome
SimonHawesome

Reputation: 1300

In Vue 3, you have to use resolveComponent() instead of the component string directly. Pop it into a variable and use it as follows

import {createApp, h, resolveComponent} from 'vue';
import helloWorldComponent from './components/helloWorld.vue'

const app = createApp({
  components: {
    'helloWorld': helloWorldComponent,
  },
  render: () => {
    const component = resolveComponent('helloWorld');
    return h(component)
  }
});

Upvotes: -1

Felipe Malara
Felipe Malara

Reputation: 1914

Can you try using it like this?
Within the setup, as mentioned here in their doc

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
      )
  }
}

Upvotes: 0

thinker12
thinker12

Reputation: 34

Use resolveComponent to handle your component name.

Upvotes: 1

l wonder
l wonder

Reputation: 1

I think it's because the component doesn't used in the "h" function. The h() called is separately to your app which create by creatApp.

Upvotes: -1

Related Questions