Vue3 render() function


Vue3 选项式 APIVue3 Options API

render()The function is a very important function in Vue3; its purpose is to generate the virtual DOM of components. The virtual DOM is a lightweight JavaScript object that Vue uses to describe the real DOM.

Throughrender()function, Vue can efficiently update and render pages.

Relationship with templates

In Vue, we usually usetemplateto define the structure of a component. The template is ultimately compiled intorender()function. Therefore,render()function is the underlying implementation of the template.

Use cases

render()The function is usually used in the following scenarios:

  • When component structure needs to be dynamically generated.
  • When DOM needs to be manipulated directly.
  • In scenarios with high performance requirements, manually optimize rendering logic.

Basic syntax of render() function

render()The function receives one parameter, Vue'shfunction (also calledcreateElementfunction), used to create virtual DOM nodes.

Example

export default {
  render(h) {
    return h('div', { class: 'container' }, 'Hello, Vue3!');
  }
}

Parameter description

  1. First parameter: tag name or component name (string or component object).
  2. Second parameter: attributes object (optional), used to define DOM attributes, events, etc.
  3. Third parameter: child nodes (optional), can be a string, array, or other virtual DOM nodes.

Advanced usage of render() function

Dynamically generating child nodes

render()The function can dynamically generate child nodes based on data.

Example

export default {
  data() {
    return {
      items: ['Apple', 'Banana', 'Orange']
    }
  },
  render(h) {
    return h('ul', this.items.map(item => h('li', item)));
  }
}

Using slots

render()The function can, viathis.$slotsaccess slot content.

Example

export default {
  render(h) {
    return h('div', [
      h('header', this.$slots.header),
      h('main', this.$slots.default),
      h('footer', this.$slots.footer)
    ]);
  }
}

Rendering components

render()The function can directly render other components.

Example

import MyComponent from './MyComponent.vue';

export default {
  render(h) {
    return h(MyComponent, { props: { message: 'Hello from parent!' } });
  }
}

Optimization of render() function

Reducing unnecessary renders

Throughrender()function, you can manually control the component's rendering logic to avoid unnecessary DOM updates.

Example

export default {
  data() {
    return {
      showMessage: true
    }
  },
  render(h) {
    return this.showMessage ? h('p', 'Hello!') : null;
  }
}

Using Fragment

Vue3 supportsFragment, and you canrender()return multiple root nodes in the function.

Example

export default {
  render(h) {
    return [h('div', 'Left'), h('div', 'Right')];
  }
}

Vue3 选项式 APIVue3 Options API

Other extensions