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

How it works...


Vue lets you create components that are very lightweight as they don't have any internal
state. With this come some limitations, for example, the only place where we can put some


logic to process user input (in the form of children of the element or props) is in the render
function.


The context we passed contains the following properties:


props: This is passed by the user.
children: This is really an array of virtual nodes, children of our component in
the template. We don't have the actual HTML element here but only a
representation of it by Vue.
slots: This is a function returning the slots (can be used instead of children in
some cases).
data: This is the entire data object passed to the component.
parent: This is a reference to the parent component.

In our code, we extracted the text inside the component by doing the following:


context.children.map(c => {
return c.text
.replace(/moveTo/g, 'M')
.replace(/traceLine/g, 'L')
.replace(/closePath/g, 'z')
}).join(' ').trim()

We are taking the array of virtual nodes contained in children and mapping each node to


its text. Since we put only some text in our HTML, the array of nodes will be a singleton,


with only one node: the text we entered. Therefore, in this particular case, doing var a =


children.map(c => someFunction(c)) is then equivalent of doing var a =


[someFunction(children[0])].


We are not only extracting the text though, but we are also replacing some terms I invented
to describe svg commands, with the real commands. The join function will sew together


all the strings in the array (just one in our case) and trim will remove all the white spaces


and line breaks.

Free download pdf