Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Advanced Vue.js - Directives, Plugins, and Render Functions Chapter 17

We would like to write a triangle with a component, but we don't like attributes and we


want to write in our own language, so we would write the following to get the same result:


<orange-line>
moveTo 100 30 traceLine 200 30 traceLine 150 120 closePath
</orange-line>

This is a perfect job for a functional component because there is no state to manage, only a
translation from one component to one element.


Your HTML layout will simply look like this:


<div id="app">
<orange-line>
moveTo 100 30 traceLine 200 30 traceLine 150 120 closePath
</orange-line>
</div>

Then, lay out your functional component in your JavaScript:


const OrangeLine = {
functional: true,
render (h, context) {
return h('svg',
[]
)
}
}

You have to specify that the component will be functional with functional: true; then


the render function is slightly different than usual. The first argument is still the
createElement function, but the second passed is the context of our component.


We can access the text written inside the HTML of our component (the commands to draw)
through context.children.


You can see that I already added an empty element. Inside this, there is an empty


array of children; we will put only the element there, which is as follows:


render (h, context) {
return h('svg',
[
h('path', {
attrs: {
d: context.children.map(c => {
return c.text
.replace(/moveTo/g, 'M')
Free download pdf