Writing the view in JavaScript with render functions

Vue compiles our templates into render functions. This means that all the component views are JavaScript code in the end. Those render functions will compose the Virtual DOM tree of elements to be displayed in the page real DOM.

Most of the time, templates are fine, but you may come across cases where you need the full programmatic power of JavaScript to create a component view. Instead of specifying a template, you write a render function to your component. For example:

export default {
props: ['message'],
render (createElement) {
return createElement(
// Element or Component
'p',
// Data Object
{ class: 'content' },
// Children or Text content
this.message
)
},
}

The first argument is createElement, the function you need to call to create elements (which can be either DOM elements or Vue components). It takes up to three arguments:

  • element (required), which can be the name of an HTML tag, the ID of a registered component, or directly a component definition object. It can be a function returning one of these.
  • data (optional) is the Data Object, which specifies things such as CSS classes, props, events, and so on.
  • children (optional) is either a text string or an array of children constructed with createElement.
We will use h as an alias of createElement, the argument of the render function, since it's the common name used by everyone (and it's required by JSX as we will see in a bit). h comes from the hyperscript term describing "writing HTML using JavaScript".

The first example would be equivalent to this template:

<template>
<p class="content">{{ message }}</p>
</template>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.125.219