0
0
Vueframework~5 mins

Render function syntax in Vue

Choose your learning style9 modes available
Introduction

Render functions let you create Vue components using JavaScript instead of templates. This gives you more control over what gets shown on the screen.

You want to build a component with dynamic structure that templates can't easily handle.
You need to use JavaScript logic directly to decide what elements to show.
You want to avoid template syntax and write everything in plain JavaScript.
You are creating a library or plugin that generates components programmatically.
You want to optimize rendering performance by controlling the output precisely.
Syntax
Vue
import { h } from 'vue';

export default {
  render() {
    return h('tag', { /* props */ }, /* children */);
  }
};

The h function creates virtual DOM nodes.

The render function returns what the component should display.

Examples
Renders a simple div with text inside.
Vue
import { h } from 'vue';

export default {
  render() {
    return h('div', 'Hello world');
  }
};
Renders a button that shows an alert when clicked.
Vue
import { h } from 'vue';

export default {
  render() {
    return h('button', { onClick: () => alert('Clicked!') }, 'Click me');
  }
};
Renders a list with three items.
Vue
import { h } from 'vue';

export default {
  render() {
    return h('ul', [
      h('li', 'Item 1'),
      h('li', 'Item 2'),
      h('li', 'Item 3')
    ]);
  }
};
Sample Program

This component uses a render function to show a greeting inside a styled section. It uses JavaScript variables and returns multiple elements inside an array.

Vue
import { h, defineComponent } from 'vue';

export default defineComponent({
  name: 'Greeting',
  render() {
    const name = 'Friend';
    return h('section', { style: { padding: '1rem', border: '1px solid #ccc' } }, [
      h('h1', `Hello, ${name}!`),
      h('p', 'Welcome to learning Vue render functions.')
    ]);
  }
});
OutputSuccess
Important Notes

Remember to import h from 'vue' to create elements.

Render functions return virtual DOM nodes, not HTML strings.

You can use JavaScript fully inside render functions for flexibility.

Summary

Render functions let you build Vue components using JavaScript code.

They use the h function to create elements and return them.

This approach is useful for dynamic or complex UI logic.